606. Construct String from Binar

2017-10-01  本文已影响0人  namelessEcho

You need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way.

The null node needs to be represented by empty parenthesis pair "()". And you need to omit all the empty parenthesis pairs that don't affect the one-to-one mapping relationship between the string and the original binary tree.

递归

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public String tree2str(TreeNode t) {
        if(t==null)return "";
        StringBuilder result = new StringBuilder();
        result.append(t.val);
        StringBuilder left = construct(t.left);
        StringBuilder right = construct(t.right);
       if(left!=null)
            result.append(left);
       if((left==null&&right!=null))
            result.append("()");
        if(right!=null)
            result.append(right);
        return result.toString();
    }
    StringBuilder construct (TreeNode t)
    {
        if(t==null) return null;
         StringBuilder result = new StringBuilder();
        result.append('(');
        result.append(t.val);
        StringBuilder left = construct(t.left);
        StringBuilder right = construct(t.right);
        if(left!=null)
            result.append(left);
       if((left==null&&right!=null))
            result.append("()");
        if(right!=null)
            result.append(right);
        result.append(')');
        return result;
            
    }
}
上一篇 下一篇

猜你喜欢

热点阅读