606. Construct String from Binary Tree

T: O(n)

S: O(n)

/**
 * 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 {
    public String tree2str(TreeNode root) {
        StringBuilder sb = new StringBuilder();
        dfs(root, sb);
        return sb.toString();
    }
    private void dfs(TreeNode node, StringBuilder sb) {
        if (node == null) {
            return;
        }

        // always print root first
        sb.append(node.val);
        
        // 底不要
        if (node.left == null && node.right == null) {
            return;
        }
        // left 有缺, 還是要誇好
        sb.append("(");
        dfs(node.left, sb);
        sb.append(")");
        
        // right 有缺, 不能有誇好
        if (node.right != null) {
            sb.append("(");
            dfs(node.right, sb);
            sb.append(")");
        }
        
    }
}

Last updated