- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTree_HeightOfABinaryTree.java
More file actions
Latest commit
83 lines (71 loc) · 2.18 KB
/
Copy pathTree_HeightOfABinaryTree.java
File metadata and controls
83 lines (71 loc) · 2.18 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
72
73
74
75
76
77
78
79
80
81
82
83
/*
Problem Statement: Tree: Height of a Binary Tree
Given the root node of a binary tree, you are required to compute the height of the tree. The height of a binary tree is defined as the number of edges on the longest path from the root node to a leaf node. A leaf is a node with no children.
Input Format:
The input consists of a number of integers. The first integer, n, indicates the number of nodes in the tree.
The subsequent n integers represent the values of the nodes, which are inserted into the tree following the rules of a binary search tree.
Output Format:
The output should be a single integer representing the height of the binary tree.
Constraints:
The number of nodes in the tree can range from 1 to 1000.
The value of each node will be a positive integer.
*/
importjava.util.*;
importjava.io.*;
classNode {
Nodeleft;
Noderight;
intdata;
Node(intdata) {
this.data = data;
left = null;
right = null;
}
}
classTree_HeightOfABinaryTree {
/*
class Node
int data;
Node left;
Node right;
*/
publicstaticintheight(Noderoot)
{
// Write your code here.
if(root == null)
{
return -1;
// break;
}
intleftHeight = height(root.left);
intrightHeight = height(root.right);
returnMath.max(leftHeight, rightHeight) + 1;
}
publicstaticNodeinsert(Noderoot, intdata) {
if(root == null) {
returnnewNode(data);
} else {
Nodecur;
if(data <= root.data) {
cur = insert(root.left, data);
root.left = cur;
} else {
cur = insert(root.right, data);
root.right = cur;
}
returnroot;
}
}
publicstaticvoidmain(String[] args) {
Scannerscan = newScanner(System.in);
intt = scan.nextInt();
Noderoot = null;
while(t-- > 0) {
intdata = scan.nextInt();
root = insert(root, data);
}
scan.close();
intheight = height(root);
System.out.println(height);
}
}