-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtosumtree.java
129 lines (106 loc) · 2.6 KB
/
tosumtree.java
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package binnarytree;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Stack;
public class tosumtree {
public class BinaryTree {
private class Node {
int data;
Node left;
Node right;
Node(int data, Node left, Node right) {
this.data = data;
this.left = left;
this.right = right;
}
}
private Node root = null;
private int size = 0;
BinaryTree(String s) {
Scanner scn = new Scanner(System.in);
this.root = inputfromstring(s, null);
}
private Node inputfromstring(String s, Node parent) {
if (s.length() == 0) {
return null;
}
Node node = new Node(0, null, null);
node.data = Integer.parseInt(String.valueOf(s.charAt(0)));
if (s.length() > 1) {
Stack<Character> stack = new Stack<>();
stack.push(s.charAt(1));
int i = 2;
while (!stack.isEmpty() && i < s.length()) {
if (s.charAt(i) == '(') {
stack.push(s.charAt(i));
} else if (s.charAt(i) == ')') {
stack.pop();
}
i++;
}
int end = i;
String leftsub = s.substring(2, end - 1);
// System.out.println(leftsub);
node.left = inputfromstring(leftsub, node);
if (end + 1 < s.length() - 1) {
String rightsub = s.substring(end + 1, s.length() - 1);
node.right = inputfromstring(rightsub, node);
}
}
return node;
}
public void display() {
display(this.root);
}
private void display(Node parent) {
String str = "";
if (parent.left != null) {
str += parent.left.data + " => ";
} else {
str += "End => ";
}
str += parent.data;
if (parent.right != null) {
str += " <= " + parent.right.data;
} else {
str += " <= End";
}
System.out.println(str);
if (parent.left != null) {
display(parent.left);
}
if (parent.right != null) {
display(parent.right);
}
}
public void tosumtree() {
tosumtree(this.root);
}
private int tosumtree(Node parent) {
if (parent == null) {
return 0;
}
if (parent.left == null && parent.right == null) {
int temp = parent.data;
parent.data = 0;
return temp;
}
int left = tosumtree(parent.left);
int right = tosumtree(parent.right);
int temp = parent.data;
parent.data = left + right;
return parent.data + temp;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
// 10 true 20 true 40 false false true 50 false false true 30 true 60 false
// false true 73 false false
tosumtree m = new tosumtree();
BinaryTree tree = m.new BinaryTree("4(2(3)(1))(6(1))");
tree.display();
System.out.println();
tree.tosumtree();
tree.display();
}
}