Skip to content

Commit 7538785

Browse files
Create Binary Tree To Sum Tree
1 parent 7c023c9 commit 7538785

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

Binary Tree To Sum Tree

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
class Node{
2+
int data;
3+
Node left;
4+
Node right;
5+
Node (int data){
6+
this.data=data;
7+
left=right=null;
8+
}
9+
10+
}
11+
12+
class tree{
13+
Node root;
14+
int sum(Node n){
15+
int left=0;
16+
int right=0;
17+
if(n.left!=null){
18+
left=sum(n.left);
19+
}
20+
if(n.right!=null){
21+
right=sum(n.right);
22+
}
23+
int temp=n.data;
24+
n.data=left+right;
25+
return (left+right+temp);
26+
}
27+
void dfs(Node n){
28+
System.out.print(n.data+" ");
29+
if(n.left!=null){
30+
dfs(n.left);
31+
}
32+
if(n.right!=null){
33+
dfs(n.right);
34+
}
35+
}
36+
37+
}
38+
39+
40+
public class Implementation {
41+
public static void main(String []args){
42+
tree t=new tree();
43+
t.root=new Node(10 );
44+
t.root.right=new Node(30);
45+
t.root.left=new Node(20);
46+
t.root.left.right=new Node(60);
47+
t.root.left.left=new Node(40);
48+
t.dfs(t.root);
49+
t.sum(t.root);
50+
System.out.println();
51+
t.dfs(t.root);
52+
}
53+
}

0 commit comments

Comments
 (0)