-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryHeight.java
More file actions
56 lines (52 loc) · 1.5 KB
/
BinaryHeight.java
File metadata and controls
56 lines (52 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
class Node{
int data;
Node left;
Node right;
//call constructor
public Node(int data){
this.data=data;
this.left=null;
this.right=null;
}
}
public class BinaryHeight{
// public static int treeHeight(Node root){
// //base case
// if(root ==null){
// return 0;
// }
// int leftpart =treeHeight(root.left);
// int Rightpart = treeHeight(root.right);
// int ans = Math.max(leftpart, Rightpart)+1;
// return ans;
// }
// public static int countNodes(Node root){
// //base case
// if(root==null){
// return 0;
// }
// int Left_Count = countNodes(root.left);
// int Right_Count = countNodes(root.right);
// int ans = Left_Count+Right_Count+1;
// return ans;
// }
public static int sum(Node root){
//base case
if(root==null){
return 0;
}
//call recursively for right and left portion to cal the sum
int left_Sum = sum(root.left);
int right_Sum = sum(root.right);
int ans = left_Sum+right_Sum+root.data;
return ans;
}
public static void main(String[] args){
Node root = new Node(3);
root.left = new Node(2);
root.right = new Node(1);
root.right.left =new Node(4);
root.right.right =new Node(5);
System.out.println("Sum is "+ sum(root));
}
}