LeetCode 606. Construct String from Binary Tree
考点 | 难度 |
---|---|
String | Easy |
题目
Given the root of a binary tree, construct a string consisting of parenthesis and integers from a binary tree with the preorder traversal way, and return it.
Omit all the empty parenthesis pairs that do not affect the one-to-one mapping relationship between the string and the original binary tree.
思路
1 没有left child,没有right child:不需要括号
2 只有left child:括号 + left child
3 只有right child:空括号 + 括号 + right child
4 两个都有:括号 + left child + 括号 + right child
因为3和4都需要两个括号,可以放在一个条件下写。
答案
public String tree2str(TreeNode t) {
if(t==null)
return "";
if(t.left==null && t.right==null)
return t.val+"";
if(t.right==null)
return t.val+"("+tree2str(t.left)+")";
return t.val+"("+tree2str(t.left)+")("+tree2str(t.right)+")";
}