原题链接:Leetcode 606. Construct String from Binary Tree
Given the root of a binary tree, construct a string consisting of parenthesis and integers from a binary tree with the preorder traversal way, and return it.
Omit all the empty parenthesis pairs that do not affect the one-to-one mapping relationship between the string and the original binary tree.
Example 1:
Input: root = [1,2,3,4]
Output: "1(2(4))(3)"
Explanation: Originally, 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: root = [1,2,3,null,4]
Output: "1(2()(4))(3)"
Explanation: Almost the same as the first example, except we cannot omit the first parenthesis pair to break the one-to-one mapping relationship between the input and the output.
Constraints:
- The number of nodes in the tree is in the range [1, 104].
- -1000 <= Node.val <= 1000
方法一:递归
思路:
首先如果是空树,可以直接返回;
根据孩子结点,一共有四种情况:
- 左右孩子都有,那么左右孩子外面都需要括号
- 左右孩子都无,那么左右孩子外面都不需要括号
- 只有左孩子,那么左孩子外面需要括号,右孩子外面不需要
- 只有右孩子,那么左右孩子外面都需要括号
c++代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
string tree2str(TreeNode *root) {
// 树为空 直接返回
if (root == nullptr) {
return "";
}
// 左右孩子都没有
if (root->left == nullptr && root->right == nullptr) {
return to_string(root->val);
}
// 只有左孩子
if (root->right == nullptr) {
return to_string(root->val) + "(" + tree2str(root->left) + ")";
}
// 左右孩子都有 以及 只有右孩子
return to_string(root->val) + "(" + tree2str(root->left) + ")(" + tree2str(root->right) + ")";
}
};
复杂度分析:
- 时间复杂度:O(n) n个结点
- 空间复杂度:O(n) 递归最深的情况有n层,栈的大小为n