Leetcode606. Construct String from Binary Tree
来源:互联网 发布:淘宝内部优惠券微信群 编辑:程序博客网 时间:2024/06/03 13:47
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.
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.
题目分析:关于树的算法题,首先第一步考虑递归算法。这道题也不例外,也是用递归去实现。
代码:
class Solution {public: string tree2str(TreeNode* t) { if (t == NULL) return ""; string s = to_string(t->val); if (t->left) s += '(' + tree2str(t->left) + ')'; else if (t->right) s += "()"; if (t->right) s += '(' + tree2str(t->right) + ')'; return s; }};
阅读全文
0 0
- LeetCode606:Construct String from Binary Tree
- Leetcode606. Construct String from Binary Tree
- python--leetcode606. Construct String from Binary Tree
- 第十六周:( LeetCode606) Construct String from Binary Tree(c++)
- Construct String from Binary Tree
- String:606. Construct String from Binary Tree
- Leetcode-536. Construct Binary Tree from String
- 536. Construct Binary Tree from String
- 536. Construct Binary Tree from String
- [leetcode]606. Construct String from Binary Tree
- 606. Construct String from Binary Tree
- 606. Construct String from Binary Tree
- [leetcode]: 606. Construct String from Binary Tree
- [LeetCode] 606. Construct String from Binary Tree
- 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
- 使用NDK编译FFmpeg到Android下使用
- Dubbo分布式服务框架入门(附工程)
- 既存既取 文件服务器优化
- 中序线索化二叉树
- struct
- Leetcode606. Construct String from Binary Tree
- sql server 脚本插入一百五十万数据
- java Collection集合知识点整理(疯狂java讲义读书笔记)
- Could not publish server configuration for XXXXX
- 常用基础类
- Paint
- 深入理解:overflow:hidden——溢出,坍塌,清除浮动
- [C#]浅谈协变与逆变
- iOS数据库追加字段方法例子