forked from dheeraj-2000/dsalgo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTree.java
More file actions
74 lines (61 loc) · 1.93 KB
/
BinaryTree.java
File metadata and controls
74 lines (61 loc) · 1.93 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
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package CompetitiveCoding;
/**
*
* @author taher
*/
class Node
{
int data;
Node left, right;
Node(int item)
{
data = item;
left = right = null;
}
}
class BinaryTree
{
Node root;
// Convert a given tree to a tree where every node contains sum of
// values of nodes in left and right subtrees in the original tree
int toSumTree(Node node)
{
if(node == null)
return 0;
int oldVal = node.data;
node.data = toSumTree(node.left) + toSumTree(node.right);
return node.data + oldVal;
}
// A utility function to print inorder traversal of a Binary Tree
void printInorder(Node node)
{
if (node == null)
return;
printInorder(node.left);
System.out.print(node.data + " ");
printInorder(node.right);
}
/* Driver function to test above functions */
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
/* Constructing tree given in the above figure */
tree.root = new Node(10);
tree.root.left = new Node(-2);
tree.root.right = new Node(6);
tree.root.left.left = new Node(8);
tree.root.left.right = new Node(-4);
tree.root.right.left = new Node(7);
tree.root.right.right = new Node(5);
tree.toSumTree(tree.root);
// Print inorder traversal of the converted tree to test result
// of toSumTree()
System.out.println("Inorder Traversal of the resultant tree is:");
tree.printInorder(tree.root);
}
}