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;    }};


原创粉丝点击