LeetCode
来源:互联网 发布:手机淘宝上的积分在哪 编辑:程序博客网 时间:2024/06/06 18:19
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.
Subscribe to see which companies asked this question.
题意:先序遍历输出二叉树。右节点不存在时可不输出括号,左节点不存在时需输出空括号。
嘛。。太久不敲代码,心情复杂。。。居然写了一阵子。。。
不过刚知道C++里有 to_string() 这种用法,神奇
/** * 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 ans = ""; if (t == NULL) return ans; ans += to_string(t->val); if (t->left != NULL || t->right != NULL) ans += solve(t->left); if (t->right != NULL) ans += solve(t->right); return ans; } string solve(TreeNode* t) { string ans = ""; if (t == NULL) return "()"; ans += "(" + to_string(t->val); if (t->left != NULL || t->right != NULL) ans += solve(t->left); if (t->right != NULL) ans += solve(t->right); ans += ")"; return ans; }};
阅读全文
0 0
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- leetcode
- leetCode
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode:
- leetcode
- spring事物管理
- JQuery 易混点
- 利用可变长参数实现,批量参数空校验
- MySQL不支持远程连接的解决办法
- Python中的random模块
- LeetCode
- session会话保持
- 窄带信号和宽带信号的区别和联系
- Spring 核心组件工作原理简析
- 博客近期的写作学习目标
- 【框架学习】myBatis
- matlab中进行二维平面中有向矩形相交探测计算OBB dection
- 170618 如何利用pandas将numpy数组导出生成excel
- R-CNN,SPP-NET, Fast-R-CNN,Faster-R-CNN, YOLO, SSD系列深度学习检测方法梳理