【题目】
你需要采用前序遍历的方式,将一个二叉树转换成一个由括号和整数组成的字符串。
空节点则用一对空括号 “()” 表示。而且你需要省略所有不影响字符串与原始二叉树之间的一对一映射关系的空括号对。
示例 1:
输入: 二叉树: [1,2,3,4]
1
/
2 3
/
4
输出: “1(2(4))(3)”
解释: 原本将是“1(2(4)())(3())”,
在你省略所有不必要的空括号对之后,
它将是“1(2(4))(3)”。
示例 2:
输入: 二叉树: [1,2,3,null,4]
1
/
2 3
\
4
输出: “1(2()(4))(3)”
解释: 和第一个示例相似,
除了我们不能省略第一个对括号来中断输入和输出之间的一对一映射关系。
【代码】
class Solution:
def tree2str(self, root: TreeNode) -> str:
ans=[]
left_cnt=0
right_cnt=0
def visit(root):
if not root:
return
ans.append(str(root.val))
flag=0
if not root.left and root.right:
flag=1
ans.append("(")
visit(root.left)
ans.append(")")
if ans[-2]=='(' and ans[-1]==')' and flag!=1:
ans.pop()
ans.pop()
ans.append("(")
visit(root.right)
ans.append(")")
if ans[-2]=='(' and ans[-1]==')':
ans.pop()
ans.pop()
visit(root)
return "".join(ans)
【方法2】
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def tree2str(self, root: TreeNode) -> str:
ans=[]
def visit(root):
if not root:
return
flag=1
ans.append("("+str(root.val))
if not root.left and not root.right:
ans.append(")")
flag=0
elif not root.left and root.right:
ans.append("()")
visit(root.left)
visit(root.right)
if flag:
ans.append(")")
visit(root)
return "".join(ans)[1:-1]
【方法3】
class Solution(object):
def tree2str(self, t):
if not t:
return ""
if not t.left and not t.right:
return str(t.val)
result = str(t.val)
if t.left:
result += "(" + self.tree2str(t.left) + ")"
else:
result += "()"
if t.right:
result += "(" + self.tree2str(t.right) + ")"
return result
【方法4】
class Solution:
def tree2str(self, root: TreeNode) -> str:
if not root:
return ""
if not root.left and not root.right:
return str(root.val)
if not root.right:
return str(root.val)+"("+str(self.tree2str(root.left))+")"
return str(root.val)+"("+str(self.tree2str(root.left))+")("+str(self.tree2str(root.right))+")"
【迭代 方法5 java版本】
public class Solution {
public String tree2str(TreeNode t) {
if (t == null)
return "";
Stack < TreeNode > stack = new Stack < > ();
stack.push(t);
Set < TreeNode > visited = new HashSet < > ();
StringBuilder s = new StringBuilder();
while (!stack.isEmpty()) {
t = stack.peek();
if (visited.contains(t)) {
stack.pop();
s.append(")");
} else {
visited.add(t);
s.append("(" + t.val);
if (t.left == null && t.right != null)
s.append("()");
if (t.right != null)
stack.push(t.right);
if (t.left != null)
stack.push(t.left);
}
}
return s.substring(1, s.length() - 1);
}
}