LeetCode 606 Construct String from Binary Tree
2017-07-24 22:54
351 查看
题目大意为给一个二叉树,求它的先序遍历生成的字符串,子节点放在括号中。
通过观察可以得到规律
子节点不为空,则左子节点的括号一定有。
右子节点不为空,则右子节点的括号一定有。
所以可以通过dfs先序遍历,加上上述的判断条件写出函数。
题目链接
代码如下:
通过观察可以得到规律
子节点不为空,则左子节点的括号一定有。
右子节点不为空,则右子节点的括号一定有。
所以可以通过dfs先序遍历,加上上述的判断条件写出函数。
题目链接
代码如下:
class Solution { public: string ans; string getString(const int n) { stringstream newstr; newstr << n; return newstr.str(); } void dfs(TreeNode* node) { ans += getString(node->val); if (node->left || node->right) { ans += "("; if (node->left) dfs(node->left); ans += ")"; if (node->right) { ans += "("; dfs(node->right); ans += ")"; } } } string tree2str(TreeNode* t) { if (t != NULL) dfs(t); return ans; } };
相关文章推荐
- leetcode 606 Construct String from Binary Tree
- 【LeetCode 606】 Construct String from Binary Tree (C++)
- LeetCode 606.[DFS] Construct String from Binary Tree
- LeetCode - 606 - Construct String from Binary Tree
- LeetCode 606:Construct String from Binary Tree (c++)
- LeetCode@Tree_606_Construct_String_from_Binary_Tree
- leetcode(606):Construct String from Binary Tree
- LeetCode 606 Construct String from Binary Tree
- 606. Construct String from Binary Tree
- [LeetCode] Construct Binary Tree from String 从字符串创建二叉树
- Leetcode之Construct String from Binary Tree 问题
- 606. Construct String from Binary Tree
- 606. Construct String from Binary Tree
- [LeetCode] Construct String from Binary Tree 根据二叉树创建字符串
- 606. Construct String from Binary Tree
- 606. Construct String from Binary Tree
- 606. Construct String from Binary Tree
- 606. Construct String from Binary Tree
- [Leetcode] 536. Construct Binary Tree from String 解题报告
- LeetCode之Construct String from Binary Tree(Kotlin)