美文网首页
606. Construct String from Binar

606. Construct String from Binar

作者: namelessEcho | 来源:发表于2017-10-01 15:26 被阅读0次

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;
            
    }
}

相关文章

网友评论

      本文标题:606. Construct String from Binar

      本文链接:https://www.haomeiwen.com/subject/oxwoextx.html