606. Construct String from Binary Tree

606. Construct String from Binary Tree

Question

Given the root of a binary tree, construct a string consisting of parenthesis and integers from a binary tree with the preorder traversal way, and return it.

Omit all the empty parenthesis pairs that do not affect the one-to-one mapping relationship between the string and the original binary tree.

Solution

DFS搜索,先序遍历到每个节点将其加入StringBuffer。
如果当前节点有左子节点或右子节点,则递归左子节点,并在前后添加一对括号。(如果有右子节点的情况即使左子节点为空也需要添加一对括号加以区别。)
如果当前节点有右子节点,则递归右子节点,并在前后添加一对括号。

Code

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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
StringBuffer sb;
public String tree2str(TreeNode root) {
sb = new StringBuffer();
dfs(root);
return sb.toString();
}

private void dfs(TreeNode root){
if(root == null) return;
sb.append(root.val);

boolean hasLeft = root.left != null, hasRight = root.right != null;

if(hasLeft || hasRight) sb.append("(");
dfs(root.left);
if(hasLeft || hasRight) sb.append(")");

if(hasRight) sb.append("(");
dfs(root.right);
if(hasRight) sb.append(")");
}
}
Author

Xander

Posted on

2022-09-06

Updated on

2022-09-06

Licensed under

Comments