Construct Binary Tree from String

You need to construct a binary tree from a string consisting of parenthesis and integers.

The whole input represents a binary tree. It contains an integer followed by zero, one or two pairs of parenthesis. The integer represents the root's value and a pair of parenthesis contains a child binary tree with the same structure.

You always start to construct the left child node of the parent first if it exists.

Example:

Input: "4(2(3)(1))(6(5))"
Output: return the tree root node representing the following tree:

       4
     /   \
    2     6
   / \   / 
  3   1 5   

 

Note:

  1. There will only be '('')''-' and '0' ~ '9' in the input string.
  2. An empty tree is represented by "" instead of "()".

思路:這題可以跟 Brace Expansion聯合起來一起看,都是遞歸循環,找到中間括號的內容,然後做dfs;

注意,這題實際上是要把左括號和右括號給去掉的,也就是內部循環的時候,其實找到左邊界和右邊界之後,還是把左邊和右邊的括號給去掉了,剛開始爲什麼不去掉,因爲剛開始進來的時候是有root的,但是如果循環右邊的時候,一定要把左右兩個括號給去掉。否則,找到左括號之後,會出現空的root,是不可以的。以下這種解法是O(n^2). 用全局變量index,掃一遍,那麼就是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 TreeNode str2tree(String s) {
        if(s == null || s.length() == 0) {
            return null;
        }
        int i = s.indexOf('(');
        if(i == -1) {
            return new TreeNode(Integer.parseInt(s));
        }
        // 剛開始 進來是有root的,所以沒問題;
        TreeNode root = new TreeNode(Integer.parseInt(s.substring(0, i)));
        // find corresponding ) index;
        int cnt = 0;
        int j = i;
        while(j < s.length()) {
            if(s.charAt(j) == '(') {
                cnt++;
            } else if(s.charAt(j) == ')') {
                cnt--;
            }
            if(cnt == 0) {
                break;
            }
            j++;
        }
        root.left = str2tree(s.substring(i + 1, j));
        
        // 左邊有括號,那麼右邊肯定有對應的括號,所以去掉頭尾;否則下一次循環會出現空root;
        if(j != s.length() - 1) {
            root.right = str2tree(s.substring(j + 2, s.length() - 1));
        }
        return root; 
    }
}

 思路2:用全局變量,remove左右兩個括號;O(N); 注意都是(開頭代表遇見左邊和右邊的node,不是),以爲代碼把左右兩個配對的括號都去掉了;

/**
 * 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 {
    private int pos = -1;
    public TreeNode str2tree(String s) {
        pos++; // remove (
        if(pos >= s.length()) {
            return null;
        }
        int start = pos;
        while(pos < s.length()) {
            if(s.charAt(pos) == '(' || s.charAt(pos) == ')') {
                break;
            }
            pos++;
        }
        TreeNode root = new TreeNode(Integer.parseInt(s.substring(start, pos)));
        if(pos < s.length() && s.charAt(pos) == '(') { // 遇見一個左邊的node;(開頭;
            root.left = str2tree(s);
            if(pos < s.length() && s.charAt(pos) == '(') { // 遇見一個有右邊的node,也是(開頭;
                root.right = str2tree(s);
            }
        }
        pos++; // remove );
        return root;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章