LeetCode606 Construct String from Binary Tree


题目

LeetCode606 Construct String from Binary Tree

思路

二叉树的简单遍历.

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* 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 dfs(TreeNode* t) {
if (t == NULL) return "";
if (t->left == NULL && t->right == NULL) return to_string(t->val);
string ret = to_string(t->val) + "(" + dfs(t->left) + ")";
if (t->right) ret += "(" + dfs(t->right) + ")";
return ret;
}
string tree2str(TreeNode* t) {
return dfs(t);
}
};