-
Notifications
You must be signed in to change notification settings - Fork 81
Expand file tree
/
Copy pathHeightTree.java
More file actions
80 lines (55 loc) · 1.62 KB
/
HeightTree.java
File metadata and controls
80 lines (55 loc) · 1.62 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
package BinaryTree;
import java.util.Scanner;
public class HeightTree {
public static BinaryTreeNode<Integer> treeInputBetter(boolean isRoot,int parentData,boolean isLeft) {
if(isRoot) {
System.out.print("Enter Root Data: ");
}
else {
if(isLeft) {
System.out.print("Enter left child of "+parentData +" : ");
}
else {
System.out.print("Enter right child of "+parentData+" : ");
}
}
Scanner sc = new Scanner(System.in);
int rootData=sc.nextInt();
if(rootData == -1) {
return null;
}
BinaryTreeNode<Integer> root = new BinaryTreeNode<Integer>(rootData);
BinaryTreeNode<Integer> leftChild = treeInputBetter(false,rootData,true);
BinaryTreeNode<Integer> rightChild = treeInputBetter(false,rootData,false);
root.left=leftChild;
root.right=rightChild;
return root;
}
public static void printTree(BinaryTreeNode<Integer> root) {
if(root == null) {
return;
}
System.out.print(root.data + ":" );
if(root.left != null) {
System.out.print("L" + root.left.data + " ,");
}
if(root.right !=null) {
System.out.print(" R"+root.right.data);
}
System.out.println();
printTree(root.left);
printTree(root.right);
}
public static int height(BinaryTreeNode<Integer> root) {
if(root == null) {
return 0;
}
return Math.max(height(root.left), height(root.right)) + 1 ;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
BinaryTreeNode<Integer> root = treeInputBetter(true, 0, true);
System.out.println(height(root));
// printTree(root);
}
}