zoukankan      html  css  js  c++  java
  • Java实现 LeetCode 606 根据二叉树创建字符串(遍历树)

    606. 根据二叉树创建字符串

    你需要采用前序遍历的方式,将一个二叉树转换成一个由括号和整数组成的字符串。

    空节点则用一对空括号 “()” 表示。而且你需要省略所有不影响字符串与原始二叉树之间的一对一映射关系的空括号对。

    示例 1:

    输入: 二叉树: [1,2,3,4]

           1
         /   
        2     3
       /    
      4     
    

    输出: “1(2(4))(3)”

    解释: 原本将是“1(2(4)())(3())”,
    在你省略所有不必要的空括号对之后,
    它将是“1(2(4))(3)”。
    示例 2:

    输入: 二叉树: [1,2,3,null,4]

       1
     /   
    2     3
       
      4 
    

    输出: “1(2()(4))(3)”

    解释: 和第一个示例相似,
    除了我们不能省略第一个对括号来中断输入和输出之间的一对一映射关系。

    PS:
    遍历树

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
          public String tree2str(TreeNode t) {
            StringBuilder sb = new StringBuilder();
            doTree2str(t, sb);
            return sb.toString();
        }
        
        private void doTree2str(TreeNode t, StringBuilder sb) {
            if (t != null) {
                sb.append(t.val);
                if (t.left != null || t.right != null) {
                    sb.append('(');
                    doTree2str(t.left, sb);
                    sb.append(')');
                    if (t.right != null) {
                        sb.append('(');
                        doTree2str(t.right, sb);
                        sb.append(')');
                    }
                }
            }
        }
    }
    
  • 相关阅读:
    Logwatch的配置与使用
    Redirect HTTP to HTTPS on Tomcat
    RedHat7搭建yum源服务器
    卸载RedHat7自带的yum,安装并使用网易163源
    15个Linux Yum命令实例--安装/卸载/更新
    GitHub详细教程
    RedHat7 Git 安装使用
    RedHat7 SELinux
    RedHat7配置IdM server
    IIS Shared Configuration
  • 原文地址:https://www.cnblogs.com/a1439775520/p/13075351.html
Copyright © 2011-2022 走看看