File tree 1 file changed +76
-0
lines changed
Course 2 - Data Structures in JAVA/Lecture 11 - Binary Trees I
1 file changed +76
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ For a given Binary Tree of integers, find and return the height of the tree.
3
+ Example:
4
+ 10
5
+ / \
6
+ 20 30
7
+ / \
8
+ 40 50
9
+
10
+ Height of the given tree is 3.
11
+ Height is defined as the total number of nodes along the longest path from the root to any of the leaf node.
12
+
13
+ Input Format:
14
+ The first and the only line of input will contain the node data, all separated by a single space.
15
+ Since -1 is used as an indication whether the left or right node data exist for root, it will not be a part of the node data.
16
+
17
+ Output Format:
18
+ The first and the only line of output prints the height of the given binary tree.
19
+ Note: You are not required to print anything explicitly. It has already been taken care of.
20
+
21
+ Constraints:
22
+ 0 <= N <= 10^5
23
+ Where N is the total number of nodes in the binary tree.
24
+ Time Limit: 1 sec
25
+
26
+ Sample Input 1:
27
+ 10 20 30 40 50 -1 -1 -1 -1 -1 -1
28
+ Sample Output 1:
29
+ 3
30
+
31
+ Sample Input 2:
32
+ 3 -1 -1
33
+ Sample Output 2:
34
+ 1
35
+ */
36
+
37
+ /*
38
+
39
+ Following is the structure used to represent the Binary Tree Node
40
+
41
+ class BinaryTreeNode<T> {
42
+ T data;
43
+ BinaryTreeNode<T> left;
44
+ BinaryTreeNode<T> right;
45
+
46
+ public BinaryTreeNode(T data) {
47
+ this.data = data;
48
+ this.left = null;
49
+ this.right = null;
50
+ }
51
+ }
52
+
53
+ */
54
+
55
+ public class Solution {
56
+
57
+ public static int height(BinaryTreeNode<Integer> root) {
58
+ //Your code goes here
59
+ if (root==null)
60
+ {
61
+ return 0;
62
+ }
63
+
64
+ int smallLeftOutput=height(root.left);
65
+ int smallRightOutput=height(root.right);
66
+ if (smallLeftOutput>smallRightOutput)
67
+ {
68
+ return smallLeftOutput+1;
69
+ }
70
+ else
71
+ {
72
+ return smallRightOutput+1;
73
+ }
74
+ }
75
+
76
+ }
You can’t perform that action at this time.
0 commit comments