606. Construct String from Binary Tree

来源:互联网 发布:薛之谦的淘宝店叫什么 编辑:程序博客网 时间:2024/06/07 23:08

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.

做了好多二叉树的问题,得出了一点点经验。其实无非是要考虑一下情况:

1. root == NULL: 有时候可以作为递归的出口

2. root->left == NULL && root->right == NULL:叶子节点

3. root->left != NULL && root->right == NULL:没有右子树的节点

4. root->left == NULL && root->right != NULL:没有左子树的节点

5. root->left != NULL && root->right != NULL :普通的非叶子节点

感觉大部分二叉树问题都可以从这五种情况考虑,因为能力有限,看到二叉树的第一反应都是用递归,所以个人的思路一般都是先考虑递归出口,就是上述情况1和情况2. 然后由特殊到一般,构造出整个解。

贴出来自己的递归代码,将来在研究迭代法吧。

这个题有一点注意的就是节点值是int,需要利用to_string方法转换成string才能直接相加减,貌似java当中会自动转换。

/** * 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) {        if (t == NULL) return "";        if (t->left == NULL && t->right == NULL) {            return to_string(t->val);        }         if (t->left != NULL && t->right == NULL) {            return to_string(t->val) + "(" + tree2str(t->left) + ")";        }        if (t->left == NULL && t->right != NULL) {            return to_string(t->val) + "()" + "(" + tree2str(t->right) + ")";        }        return to_string(t->val) + "(" + tree2str(t->left) + ")" + "(" + tree2str(t->right) + ")";            }    };