zoukankan      html  css  js  c++  java
  • LeetCode Construct String from Binary Tree

    原题链接在这里:https://leetcode.com/problems/construct-string-from-binary-tree/#/description

    题目:

    You need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way.

    The null node needs to be represented by empty parenthesis pair "()". And you need to omit all the empty parenthesis pairs that don't affect the one-to-one mapping relationship between the string and the original binary tree.

    Example 1:

    Input: Binary tree: [1,2,3,4]
           1
         /   
        2     3
       /    
      4     
    
    Output: "1(2(4))(3)"
    
    Explanation: Originallay it needs to be "1(2(4)())(3()())",
    but you need to omit all the unnecessary empty parenthesis pairs.
    And it will be "1(2(4))(3)".

    Example 2:

    Input: Binary tree: [1,2,3,null,4]
           1
         /   
        2     3
           
          4 
    
    Output: "1(2()(4))(3)"
    
    Explanation: Almost the same as the first example,
    except we can't omit the first parenthesis pair to break the one-to-one mapping relationship between the input and the output.

    题解:

    类似Binary Tree Preorder Traversal.

    Method 1时recursion方法. 但要注意几种特殊情况:

    在left child, right child 都是null的情况下是不iterate child 的

    如果left child 和right child 中至少有一个不是null 就iterate child 此时无论left child 是否为null 都需要 iterate

    在右侧child 不为null时才iterate.

    Time Complexity: O(n). 每个节点走了一遍. Space: O(logn), 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 public class Solution {
    11     public String tree2str(TreeNode t) {
    12         StringBuilder sb = new StringBuilder();
    13         preorderTraversal(t, sb);
    14         return sb.toString();
    15     }
    16     
    17     private void preorderTraversal(TreeNode t, StringBuilder sb){
    18         if(t == null){
    19             return;
    20         }
    21         
    22         sb.append(t.val);
    23         if(t.left == null && t.right == null){
    24             return;
    25         }
    26         
    27         // 到此说明左右child至少有一个不是null 那么就要iterate left child
    28         sb.append("(");
    29         preorderTraversal(t.left, sb);
    30         sb.append(")");
    31         
    32         // right child在不是null时才会iterate
    33         if(t.right != null){
    34             sb.append("(");
    35             preorderTraversal(t.right, sb);
    36             sb.append(")");
    37         }
    38     }
    39 }

    Method 2是iteration方法. 类似Binary Tree Preorder Traversal的method 2.

    多了visited 来标记已经iterate的点. 在peek stack后如果iterate过了就pop stack 并把")"加到结果中.

    Time Complexity: O(n). n是节点个数. Space: O(n).

    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 public class Solution {
    11     public String tree2str(TreeNode t) {
    12         StringBuilder sb = new StringBuilder();
    13         if(t == null){
    14             return sb.toString();
    15         }
    16         
    17         Stack<TreeNode> stk = new Stack<TreeNode>();
    18         stk.push(t);
    19         HashSet<TreeNode> visited = new HashSet<TreeNode>();
    20         while(!stk.isEmpty()){
    21             TreeNode tn = stk.peek();
    22             if(visited.contains(tn)){
    23                 stk.pop();
    24                 sb.append(")");
    25             }else{
    26                 visited.add(tn);
    27                 sb.append("(" + tn.val);
    28                 if(tn.left==null && tn.right!=null){
    29                     sb.append("()");
    30                 }
    31                 if(tn.right != null){
    32                     stk.push(tn.right);
    33                 }
    34                 if(tn.left != null){
    35                     stk.push(tn.left);
    36                 }
    37             }
    38         }
    39         return sb.toString().substring(1,sb.length()-1);
    40     }
    41 }

    跟上Construct Binary Tree from String.

  • 相关阅读:
    qemu+chroot构建arm aarch64虚拟机
    <转>Linux环境下段错误的产生原因及调试方法小结
    <转>PCA的数学原理
    博客分类整理
    detectron2 配置记录
    如何读取部分的预训练模型
    重新配置语义分割实验环境遇到的坑
    pytorch 调整tensor的维度位置
    seg代码配置的踩坑记录
    Alienware R8外星人台式机安装双系统(WIN10+Ubuntu)的总结
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/7076384.html
Copyright © 2011-2022 走看看