Leetcode606. 由二叉树构建字符串
来源:互联网 发布:windows ce 触摸屏 编辑:程序博客网 时间:2024/05/21 10:32
Leetcode606. Construct String from Binary Tree
题目
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.
Example1:
Input: Binary tree: [1,2,3,4]
1
/ \
2 3
/
4
Output: “1(2(4))(3)”
Explanation: Originally 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)”.Example2:
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和3,其中子节点2有左子节点4,而输出的字符串为”1(2(4))(3)”。由此不难分析出:当某个节点左右两个子节点均不为空时,应加上(),并在其中加上子节点的值;而当某个节点只存在左子节点时,则可以省略右子节点对应的()。
再来看第二个例子。根节点1有左右两个子节点2和3,其中子节点2有右子节点4,而输出的字符串为”1(2()(4))(3)”。可以看出:当某个节点只存在右子节点时,则不能省略其左子节点对应的()。
分析完输出的字符串的格式要求,再来想下如何遍历二叉树。很显然,采用先序遍历的方法就可以了,在遍历的时候注意判断左右子节点是否为空,就可以顺利解决这个问题。
源代码
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: string tree2str(TreeNode* t) { if(t == NULL) { return ""; } string str = to_string(t->val); if(t->left != NULL) { str += '(' + tree2str(t->left) + ')'; } else if(t->right != NULL) { str += "()"; } if(t->right != NULL) { str += '(' + tree2str(t->right) + ')'; } return str; }};
以上只是我对这道题的一些想法,有问题还请在评论区讨论留言~
- Leetcode606. 由二叉树构建字符串
- 由字符串建立二叉树
- 由中序后序构建二叉树 Java实现
- 由前序遍历构建一个特殊的二叉树
- 由前序和中序序列构建二叉树
- 由已知的层次遍历序列构建二叉树
- 由二叉树的前序序列和中序序列构建二叉树
- 由先序中序求二叉树
- [LeetCode] 由前序和中序序列,构建二叉树
- 由前序和中序遍历构建一颗二叉树
- 题目:1385 由前序和中序构建二叉树
- 由前序遍历和中序遍历重新构建二叉树
- 如何构建二叉树
- 如何构建二叉树
- 构建二叉树实例
- 构建二叉树
- leetcode:构建二叉树
- 二叉树的构建
- 学习Python:逻辑回归算法
- 【笔试题】不同页面之间实现参数传递的几种方式
- Laravel5.4使用MongoDB作为默认的日志存储方式
- 勉励自己,今天开始写博客。
- <C语言经典100例>c11 水仙花数
- Leetcode606. 由二叉树构建字符串
- FragmentPagerAdapter刷新fragment记两点
- Python问题列表
- docker--数据卷
- [agc001e]BBQ hard
- JVM_1_运行时内存区域
- 论文:Banerjee A, Ghosh J. On Scaling Up Balanced Clustering Algorithms.[C]笔记
- SSH和SSM流程图
- 主元素 II