zoukankan      html  css  js  c++  java
  • 刷题-力扣-606. 根据二叉树创建字符串

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

    题目链接

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/construct-string-from-binary-tree
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    题目描述

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

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

    示例 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)"
    
    解释: 和第一个示例相似,
    除了我们不能省略第一个对括号来中断输入和输出之间的一对一映射关系。
    

    题目分析

    1. 根据题目描述,将二叉树根据规则生成字符串
    2. 先序遍历二叉树

    代码

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
     *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
     *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
     * };
     */
    class Solution {
    public:
        string tree2str(TreeNode* root) {
            if (!root) return "";
            if (root->left == nullptr && root->right == nullptr) return to_string(root->val);
            else if ((root->left) && (root->right)) return to_string(root->val) + "(" + tree2str(root->left) + ")(" + tree2str(root->right) + ")";
            else return  root->left ? to_string(root->val) + "(" + tree2str(root->left) + ")" : to_string(root->val) + "()(" + tree2str(root->right) + ")";
        }
    };
    
  • 相关阅读:
    国际组织
    波段
    hhgis驱动
    百度地图格式
    气象数据格式
    汽车用传感器
    无线传感器网络
    【系统软件工程师面试】7. 消息队列
    【ToDo】存储设计概述
    Arthas: Java 动态追踪技术
  • 原文地址:https://www.cnblogs.com/HanYG/p/15205681.html
Copyright © 2011-2022 走看看