[leetcode]: 606. Construct String from Binary Tree
来源:互联网 发布:程序员怎么选择公司 编辑:程序博客网 时间:2024/05/21 10:13
1.题目
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)”
原始结果 “1(2(4)())(3()())”, 去掉不必要的空括号,结果为”1(2(4))(3)”.
Example 2:
Input: Binary tree: [1,2,3,null,4]
1 / \2 3 \ 4
Output: “1(2()(4))(3)”
这里不需要去掉空括号,否则这个字符串对应的二叉树不唯一。
总结规律:
当左节点为空,右节点不为空,左节点的空括号保留。
当左节点不为空,右节点为空,右节点的空括号可以去掉
当左右节点均为空,两个空括号都要去掉。
2.分析
前序遍历,递归实现
3.代码
class Solution {public: string tree2str(TreeNode* t) { if (t == NULL) return ""; string res = to_string(t->val); if (t->left&&t->right) return res + "(" + tree2str(t->left) + ")" + "(" + tree2str(t->right) + ")"; else if (t->left) return res + "(" + tree2str(t->left) + ")"; else if (t->right) return res + "()(" + tree2str(t->right) + ")"; else return res; }};
- [leetcode]606. Construct String from Binary Tree
- [leetcode]: 606. Construct String from Binary Tree
- [LeetCode] 606. Construct String from Binary Tree
- Leetcode 606. Construct String from Binary Tree
- LeetCode: 606. Construct String from Binary Tree
- [LeetCode]606. Construct String from Binary Tree
- leetcode 606. Construct String from Binary Tree
- LeetCode 606. Construct String from Binary Tree
- leetcode: 606. Construct String from Binary Tree
- Leetcode-606. Construct String from Binary Tree
- leetcode-606. Construct String from Binary Tree
- leetcode-606. Construct String from Binary Tree
- Leetcode-536. Construct Binary Tree from String
- LeetCode 606 Construct String from Binary Tree
- LeetCode 606 Construct String from Binary Tree
- LeetCode Construct String from Binary Tree
- leetcode 606 Construct String from Binary Tree
- Construct String from Binary Tree(leetcode)
- Webstorm快捷键速记(Mac版)
- AS项目运行正常,但查看代码飘红the file size exceeds configured limit.
- SpringMVC + Freemarker 国际化
- Gson基本用法
- 无向图.md
- [leetcode]: 606. Construct String from Binary Tree
- 排名前三的python 开源 IDE
- 分类的树状处理
- jQuery转Vue项目实践总结
- 奇异值分解(Sigular Value Decomposition)
- jstl select <c:if test下拉菜单不能被选中!
- 如何对系统中设置的修改记录增加log日志
- Java 排序 Lambda
- 软件开发与设计