606. Construct String from Binary Tree
2017-09-06 11:04
399 查看
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.
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.
/*C++ Solution*/ /** * 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: int travelTree(TreeNode * t,string & str) { if(t == NULL){ return -1; } str.append(to_string(t->val)); if(t->left){ str.append("("); travelTree(t->left,str); str.append(")"); } if(t->right){ if(!t->left){ str.append("()"); } str.append("("); travelTree(t->right,str); str.append(")"); } return 0; } string tree2str(TreeNode* t) { string str; travelTree(t,str); return str; } };
/*java solution*/ /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public String str = new String(); public boolean travelTree(TreeNode t) { if(t == null){ return false; } str += Integer.toString(t.val); if(t.left!=null){ str += "("; travelTree(t.left); str += ")"; } if(t.right!=null){ if(t.left == null){ str += "()"; } str += "("; travelTree(t.right); str += ")"; } return true; } public String tree2str(TreeNode t) { travelTree(t); return str; } }
相关文章推荐
- LeetCode 606 Construct String from Binary Tree
- LeetCode 606.[DFS] Construct String from Binary Tree
- 606. Construct String from Binary 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
- 606. 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
- 606. Construct String from Binary Tree
- 606. Construct String from Binary Tree
- LeetCode 606:Construct String from Binary Tree (c++)
- LeetCode@Tree_606_Construct_String_from_Binary_Tree
- 606. Construct String from Binary Tree
- 【LeetCode 606】 Construct String from Binary Tree (C++)
- String-606-Construct String from Binary Tree
- 606. Construct String from Binary Tree