-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathBT_Problem_19.java
More file actions
101 lines (83 loc) · 1.99 KB
/
Copy pathBT_Problem_19.java
File metadata and controls
101 lines (83 loc) · 1.99 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package trees.binaryTree;
import java.util.Stack;
/*
* Problem Title :- Convert Binary tree into Sum tree.
*/
public class BT_Problem_19 {
/* A binary tree node has data, pointer to left
child and a pointer to right child */
static class Node {
int data;
Node left, right;
}
/* Helper function that allocates a new node */
static Node newNode(int data) {
Node node = new Node();
node.data = data;
node.left = node.right = null;
return (node);
}
/* This function is here just to test */
static void preOrder(Node node)
{
if (node == null)
return;
System.out.printf("%d ", node.data);
preOrder(node.left);
preOrder(node.right);
}
// function to return the index of close parenthesis
static int findIndex(String str, int si, int ei)
{
if (si > ei)
return -1;
// Inbuilt stack
Stack<Character> s = new Stack<>();
for (int i = si; i <= ei; i++) {
// if open parenthesis, push it
if (str.charAt(i) == '(')
s.add(str.charAt(i));
// if close parenthesis
else if (str.charAt(i) == ')') {
if (s.peek() == '(') {
s.pop();
// if stack is empty, this is
// the required index
if (s.isEmpty())
return i;
}
}
}
// if not found return -1
return -1;
}
// function to con tree from String
static Node treeFromString(String str, int si, int ei)
{
// Base case
if (si > ei)
return null;
// new root
Node root = newNode(str.charAt(si) - '0');
int index = -1;
// if next char is '(' find the index of
// its complement ')'
if (si + 1 <= ei && str.charAt(si+1) == '(')
index = findIndex(str, si + 1, ei);
// if index found
if (index != -1) {
// call for left subtree
root.left = treeFromString(str, si + 2, index - 1);
// call for right subtree
root.right = treeFromString(str, index + 2, ei - 1);
}
return root;
}
// Driver Code
public static void main(String[] args)
{
String str = "4(2(3)(1))(6(5))";
Node root = treeFromString(str, 0, str.length() - 1);
preOrder(root);
}
}