-
Notifications
You must be signed in to change notification settings - Fork 1
/
ConstructStringFromBinaryTree.java
42 lines (35 loc) · 1.09 KB
/
ConstructStringFromBinaryTree.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
package com.smlnskgmail.jaman.leetcodejava.easy;
import com.smlnskgmail.jaman.leetcodejava.support.TreeNode;
// https://leetcode.com/problems/construct-string-from-binary-tree/
public class ConstructStringFromBinaryTree {
private final TreeNode input;
public ConstructStringFromBinaryTree(TreeNode input) {
this.input = input;
}
public String solution() {
StringBuilder result = new StringBuilder();
result.append(input.val);
apply(input, result);
return result.toString();
}
private void apply(TreeNode node, StringBuilder part) {
if (node == null) {
return;
}
if (node.left != null) {
part.append('(');
part.append(node.left.val);
apply(node.left, part);
part.append(')');
}
if (node.right != null) {
if (node.left == null) {
part.append("()");
}
part.append('(');
part.append(node.right.val);
apply(node.right, part);
part.append(')');
}
}
}