• LeetCode 536. Construct Binary Tree from String


    原题链接在这里: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:

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

    题解:

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

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

    When count is back to 0, that means we find the string within first bracket, which is left child.

    If now, current index j is still within lenght of string, then the rest part before s.length()-1 is right child

    Time Complexity: O(s.length * h). h is tree height. 每个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 }

    Iteration Method. Use stack to perform preorder iteration. The top of stack should be current root.

    When encountering digit, get the value, create a tree node, cur. If stack is not empty, then cur node could either be stack top tree node's left child or righ child. Then also push cur node into stack.

    When encountering ')', then current level in this subtree should be finished. Pop the stack.

    Time Complexity: O(n).

    Space: O(h). Tree height.

    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         Stack<TreeNode> stk = new Stack<TreeNode>();
    17         for(int i = 0; i<s.length(); i++){
    18             char c = s.charAt(i);
    19             if(c>='0' && c<='9' || c=='-'){
    20                 int start = i;
    21                 while(i+1<s.length() && s.charAt(i+1)>='0' && s.charAt(i+1)<='9'){
    22                     i++;
    23                 }
    24                 
    25                 TreeNode cur = new TreeNode(Integer.valueOf(s.substring(start, i+1)));
    26                 if(!stk.isEmpty()){
    27                     TreeNode top = stk.peek();
    28                     if(top.left == null){
    29                         top.left = cur;
    30                     }else{
    31                         top.right = cur;
    32                     }
    33                 }
    34                 
    35                 stk.push(cur);
    36             }else if(c == ')'){
    37                 stk.pop();
    38             }
    39         }
    40         
    41         return stk.peek();
    42     }
    43 }

    跟上Construct String from Binary Tree.

  • 相关阅读:
    设计模式学习笔记——Bridge 桥接模式
    设计模式学习笔记——Adapter 适配器模式
    protoc protobuff安装
    docker-compose启动consul
    docker etcd 环境搭建
    nifi的去重方案设计(二)-外部存储mysql全局去重
    实现一套ES全文检索语法-到Lucene语法的转换工具,以实现在es外部兼容处理文本分词
    nifi的去重方案设计(一)-单队列内去重.md
    k8s 证书过期处理
    部分项目从kafka迁移至pulsar,近期使用中碰到了一些问题,勉强把大的坑踩完了,topic永驻,性能相关
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/7690096.html
Copyright © 2020-2023  润新知