- 606. Construct String from Binar
- 606. Construct String from Binar
- 606. Construct String from Binar
- 606. Construct String from Binar
- 606. Construct String from Binar
- 606. Construct String from Binar
- Leetcode PHP题解--D92 606. Constru
- 【1错-1】Construct String from Bina
- [LeetCode]606. Construct String
- 536. Construct Binary Tree from
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.
递归
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public String tree2str(TreeNode t) {
if(t==null)return "";
StringBuilder result = new StringBuilder();
result.append(t.val);
StringBuilder left = construct(t.left);
StringBuilder right = construct(t.right);
if(left!=null)
result.append(left);
if((left==null&&right!=null))
result.append("()");
if(right!=null)
result.append(right);
return result.toString();
}
StringBuilder construct (TreeNode t)
{
if(t==null) return null;
StringBuilder result = new StringBuilder();
result.append('(');
result.append(t.val);
StringBuilder left = construct(t.left);
StringBuilder right = construct(t.right);
if(left!=null)
result.append(left);
if((left==null&&right!=null))
result.append("()");
if(right!=null)
result.append(right);
result.append(')');
return result;
}
}
网友评论