zoukankan      html  css  js  c++  java
  • 606. Construct String from Binary Tree 构造二叉树字符串

    • Total Accepted: 2202
    • Total Submissions: 3988
    • Difficulty: Easy
    • Contributors:love_Fawn

    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.
    题意:把二叉树转换成字符串
    解法:先序遍历二叉树,需要处理左节点为空,右节点不为空的情况

    1. /**
    2. * Definition for a binary tree node.
    3. * public class TreeNode {
    4. * public int val;
    5. * public TreeNode left;
    6. * public TreeNode right;
    7. * public TreeNode(int x) { val = x; }
    8. * }
    9. */
    10. public class Solution {
    11. public string Tree2str(TreeNode t) {
    12. if (t == null) return "";
    13. return DFS(t);
    14. }
    15. static public string DFS(TreeNode t) {
    16. StringBuilder builder = new StringBuilder();
    17. builder.Append(t.val);
    18. if (t.left != null) {
    19. builder.Append("(");
    20. builder.Append(DFS(t.left));
    21. builder.Append(")");
    22. }
    23. if (t.right != null) {
    24. if (t.left == null) {
    25. builder.Append("()");
    26. }
    27. builder.Append("(");
    28. builder.Append(DFS(t.right));
    29. builder.Append(")");
    30. }
    31. return builder.ToString();
    32. }
    33. }






  • 相关阅读:
    python同时继承多个类且方法相同
    django扩展用户继承AbstractUser
    python中单下划线和双下划线
    django扩展用户一对一关联
    django拓展用户proxy代理
    django 内置User对象基本使用
    selenium+pthon之二----了解浏览器的相关操作方法
    最近很燥,决心沉下心来学习!
    selenium+pthon之一----环境搭建与脚本实例
    Fiddler入门三
  • 原文地址:https://www.cnblogs.com/xiejunzhao/p/6b7c16e817570b39ca5ee485537cc8bc.html
Copyright © 2011-2022 走看看