606. Construct String from Binary Tree
来源:互联网 发布:网络发言防和谐器 编辑:程序博客网 时间:2024/05/18 01:46
606. Construct String from Binary Tree
Problem
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.
Implementation
/** * 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) { string res; constructString(t, res); return res; } void constructString(TreeNode* root, string& res) { if(!root) return; res.append(to_string(root->val)); if(!root->left && !root->right) return; else if(!root->left) { res.append("()"); res.append("("); constructString(root->right, res); res.append(")"); } else if(!root->right) { res.append("("); constructString(root->left, res); res.append(")"); } else { res.append("("); constructString(root->left, res); res.append(")"); res.append("("); constructString(root->right, res); res.append(")"); } }};
阅读全文
0 0
- String:606. Construct String from Binary Tree
- [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
- 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
- 606. Construct String from Binary Tree
- 606. Construct String from Binary Tree
- 606. Construct String from Binary Tree
- 606. Construct String from Binary Tree
- 图论500题
- jsp自动刷新
- 关于第一次使用redis的这件事
- css之负外边距
- 计算机系统要素:第三章 时序逻辑
- 606. Construct String from Binary Tree
- 对开发者有用的英文网站合集
- hdu 1243 反恐训练营
- 逻辑回归
- 在一个处于CLOSE_WAIT状态下的socket上send数据,对方会毫不留情地RST(对方之前已经调用close发FIN)
- JZOJ 3505. 【NOIP2013模拟11.4A组】积木(brick)
- Android之Service
- 八皇后问题
- jzoj P1286 太空电梯