-
Notifications
You must be signed in to change notification settings - Fork 6
/
_606_Construct_String_from_Binary_Tree.java
73 lines (59 loc) · 1.39 KB
/
_606_Construct_String_from_Binary_Tree.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
package leetcode;
import java.lang.StringBuilder;
import java.util.LinkedList;
//Definition for a binary tree node.
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
/**
* 1
* / \
* 2 3
* /
* 4
*Output: "1(2(4))(3)"
**/
public class _606_Construct_String_from_Binary_Tree {
public static void main(String[] ar){
TreeNode root = new TreeNode(1);
TreeNode root2 = new TreeNode(2);
TreeNode root3 = new TreeNode(3);
TreeNode root4 = new TreeNode(4);
/* root.left = root2;
root2.left=root4;
root.right=root3;*/
root.left = root2;
root.right=root3;
root2.right=root4;
System.out.println(new _606_Construct_String_from_Binary_Tree().tree2str(root));
}
public String tree2str(TreeNode t) {
StringBuilder sb = new StringBuilder();
if(t!=null){
sb.append(t.val);
r(t,t.left,sb);
r(t,t.right,sb);
}
return sb.toString();
}
private void r(TreeNode parent,TreeNode current,StringBuilder sb){
if(current == null){
return;
}
if(parent.left == null){
if(parent.right == null){
return;
}else{
sb.append("()");
}
}
sb.append("(");
sb.append(current.val);
r(current,current.left,sb);
r(current,current.right,sb);
sb.append(")");
}
}