Construct String from Binary Tree(leetcode)
来源:互联网 发布:休闲皮鞋 知乎 编辑:程序博客网 时间:2024/06/05 11:10
Construct String from Binary Tree
- Construct String from Binary Tree
- 题目
- 解决
题目
leetcode题目
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.
解决
/** * 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 result = ""; if (t == NULL) return result; result += to_string(t->val); if (t->left != NULL) { result += "(" + tree2str(t->left) + ")"; } else if (t->right != NULL) { result += "()"; } if (t->right != NULL) { result += "(" + tree2str(t->right) + ")"; } return result; }};
阅读全文
0 0
- Leetcode-536. Construct Binary Tree from String
- [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 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
- Construct String from Binary Tree(leetcode)
- CSS实现左右滑动菜单分类
- 111
- 二分图大讲堂——彻底搞定最大匹配数(最小覆盖数)、最大独立数、最小路径覆盖、带权最优匹配
- 理解 LSTM 网络
- 织梦dede后台常见问题解决方式
- Construct String from Binary Tree(leetcode)
- 【第十三周】Kruskal算法的验证
- PHP获取用户访问IP地址的5种方法
- js 中 $(body).data('num', 1); $(body).data('num');
- 第十一周项目一 图算法库的建立
- wireshark 常用过滤命令
- Git常用命令
- 通过Web Service实现IP地址查询功能
- tensorflow softmax输出只有0或1