Construct String from Binary Tree

Construct a String consists of Integers and parenthesis from a binary tree with preorder traversing way.

Omit all unnecessary parenthesis that do not affect the one-to-one mapping of the String and Tree.

That is when the left and right subtrees are both null or the right subtree is null, we do not construct parenthesis on them.

Solution:

1. we make sure that the root is not null, or we just return "".

2. then we write a method addString(TreeNode) that returns the String of that TreeNode, which is not null.

3. we add current node to the result, and if the left and right are both null, just return. if left is null, we add "()" to the result, otherwise, we add "("+addString(left)+")". if right is not null, we add "("+addString(right)+")". return the result.

4. invoke this method addString in the main function.

Code:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public String tree2str(TreeNode t) {
        if(t == null)
            return "";
        return addString(t);
    }
    private String addString(TreeNode t){
        StringBuilder sb = new StringBuilder();
        sb.append(t.val);
        if(t.left == null && t.right == null)
            return sb.toString();
        if(t.left == null)
            sb.append("()");
        else
            sb.append("("+addString(t.left)+")");
        if(t.right != null)
            sb.append("("+addString(t.right)+")");
        return sb.toString();
    }
}
View Code

 

posted @ 2017-06-17 11:37  小风约定  阅读(55)  评论(0)    收藏  举报