-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathBT_Problem_03.java
More file actions
71 lines (55 loc) · 1.5 KB
/
Copy pathBT_Problem_03.java
File metadata and controls
71 lines (55 loc) · 1.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package trees.binaryTree;
class Node {
int data;
Node root, left, right;
public Node(int value) {
data = value;
root = left = right = null;
}
}
/*
* Problem Title :- Find the Height of a tree or Maximum Depth of a tree.
*
* Height of tree :-
* The height of a tree is the number of edges on the longest downward path
* between the root and a leaf.
*/
public class BT_Problem_03 {
Node root;
/*
* Compute the "maxDepth" of a tree --
* the number of nodes along the longest path from the root node
* down to the farthest leaf node
*/
int maxDepth(Node node) {
// base case
if (node == null)
return 0;
else {
/* compute the depth of each subtree */
int leftDepth = maxDepth(node.left);
int rightDepth = maxDepth(node.right);
/* if left is larger use left depth */
if (leftDepth > rightDepth)
return (leftDepth + 1);
/* otherwise use right depth */
else
return (rightDepth + 1);
/**
* Note: The +1 ensures that each node's contribution to the overall
* height is included as the recursion unwinds,
* ultimately providing the correct height of the tree.
*/
}
}
/* Driver program to test above functions */
public static void main(String[] args) {
BT_Problem_03 tree = new BT_Problem_03();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
System.out.println("Height of tree is : " + tree.maxDepth(tree.root));
}
}