Construct Binary Tree from String

http://www.lintcode.com/zh-cn/problem/construct-binary-tree-from-string/

/**
 * Definition of TreeNode:
 * public class TreeNode {
 * public int val;
 * public TreeNode left, right;
 * public TreeNode(int val) {
 * this.val = val;
 * this.left = this.right = null;
 * }
 * }
 */

public class Solution {
    /**
     * @param s: a string
     * @return: a root of this tree
     */
    public TreeNode str2tree(String s) {
        // write your code here
        if (s == null || s.length() == 0) {
            return null;
        }
        int i = s.indexOf("(");
        if (i <= 0) {
            return new TreeNode(Integer.parseInt(s));
        } else {
            TreeNode node = new TreeNode(Integer.parseInt(s.substring(0, i)));
            int count = 0;
            int j = i;
            while (i < s.length()) {
                char c = s.charAt(j);
                if (c == '(') {
                    count++;
                } else if (c == ')') {
                    count--;
                    if (count == 0) {
                        break;
                    }
                }
                j++;
            }
            node.left = str2tree(s.substring(i + 1, j));
            if (j < s.length() - 1) {
                node.right = str2tree(s.substring(j + 2, s.length() - 1));
            }
            return node;
        }
    }
}

你可能感兴趣的:(Construct Binary Tree from String)