您的位置:首页 > 其它

LeetCode Construct Binary Tree from String

2017-10-19 02:54 447 查看
原题链接在这里:https://leetcode.com/problems/construct-binary-tree-from-string/description/

题目:

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:

There will only be
'('
,
')'
,
'-'
and
'0'
~
'9'
in the input string.

An empty tree is represented by
""
instead of
"()"
.

题解:

找到第一个"(". 前面的就是root的值.

下面第一个括号内的就是left child. 通过leftCount来标记是否找到这层括号结束的位置. 遇到"(", leftCount++, 遇到")", leftCount--.

当leftCount归0时说明括号结束, 同时用变量start标记是left child 还是 right child的位置. 如果start还在第一个"("的位置, 这是left child, 否则是 right child.

Time Complexity: O(s.length * h). h是数的高度. 每个char可能被走过h遍. h是括号层的深度.

Space: O(h). stack space.

AC Java:

1 /**
2  * Definition for a binary tree node.
3  * public class TreeNode {
4  *     int val;
5  *     TreeNode left;
6  *     TreeNode right;
7  *     TreeNode(int x) { val = x; }
8  * }
9  */
10 class Solution {
11     public TreeNode str2tree(String s) {
12         if(s == null || s.length() == 0){
13             return null;
14         }
15
16         int leftChildOpenBracket = s.indexOf("(");
17         int rootVal = leftChildOpenBracket == -1 ? Integer.valueOf(s) : Integer.valueOf(s.substring(0, leftChildOpenBracket));
18         TreeNode root = new TreeNode(rootVal);
19
20         if(leftChildOpenBracket == -1){
21             return root;
22         }
23
24         int leftCount = 0;
25         int start = leftChildOpenBracket;
26         for(int i = start; i<s.length(); i++){
27             if(s.charAt(i) == '('){
28                 leftCount++;
29             }else if(s.charAt(i) == ')'){
30                 leftCount--;
31             }
32
33             if(leftCount==0 && start==leftChildOpenBracket){
34                 root.left = str2tree(s.substring(start+1, i));
35                 start = i+1;
36             }else if(leftCount == 0){
37                 root.right = str2tree(s.substring(start+1, i));
38             }
39         }
40         return root;
41     }
42 }


跟上Construct String from Binary Tree.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: