536. 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:
?[暴力解法]:
時間分析:
空間分析:
?[優化后]:
時間分析:
空間分析:
[奇葩輸出條件]:
[奇葩corner case]:
注意下:取數可以多取幾位,i+1位是數字時就繼續i++
[思維問題]:
感覺我在背題:幾天不背,功力全無。substring都忘了。
[英文數據結構或算法,為什么不用別的數據結構或算法]:
[一句話思路]:
[輸入量]:空:?正常情況:特大:特小:程序里處理到的特殊情況:異常情況(不合法不合理的輸入):
[畫圖]:
[一刷]:
?
[二刷]:
[三刷]:
[四刷]:
[五刷]:
? [五分鐘肉眼debug的結果]:
[總結]:
從i j中截取字符串, j應該跟隨i更新
[復雜度]:Time complexity: O() Space complexity: O()
[算法思想:迭代/遞歸/分治/貪心]:
[關鍵模板化代碼]:
?
for (int i = 0, j = i; i < s.length(); i++, j = i) {TreeNode node = new TreeNode(Integer.valueOf(s.substring(j, i + 1)));}?
[其他解法]:
[Follow Up]:
[LC給出的題目變變變]:
?[代碼風格] :
?[是否頭一次寫此類driver funcion的代碼] :
?[潛臺詞] :
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/ class Solution {public TreeNode str2tree(String s) {//corner caseif (s == null || s.length() == 0) return null;//initialization: stackStack<TreeNode> stack = new Stack<TreeNode>();//for loop: new node, get substring and appendfor (int i = 0, j = i; i < s.length(); i++, j = i) {//get cchar c = s.charAt(i);//if c is )if (c == ')') stack.pop();else if ((c >= '0' && c <= '9') || (c == '-')) {//continuewhile (i + 1 < s.length() && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '9') i++;//build new nodeTreeNode node = new TreeNode(Integer.valueOf(s.substring(j, i + 1)));if (!stack.isEmpty()) {TreeNode parent = stack.peek();//get left and appendif (parent.left != null) {parent.right = node;}else parent.left = node;}stack.push(node);}}//return the last rootreturn stack.peek() == null ? null : stack.pop();} } View Code?
轉載于:https://www.cnblogs.com/immiao0319/p/9612471.html
總結
以上是生活随笔為你收集整理的536. Construct Binary Tree from String 从括号字符串中构建二叉树的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python 归纳 (十二)_并发队列Q
- 下一篇: web 基础知识