题目要求
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.
题目分析及思路
给出一个二叉树,要求创建一个字符串,以前序遍历的顺序包含括号和二叉树中的整数。空结点用空括号对"()"表示。需要注意的一点是:不影响一一对应关系的空括号对要忽略,即当结点的左孩子结点为空时不能忽略。可以使用递归的方法,给出三个条件:1)该结点为空;2)该结点的子结点为空;3)该结点的右孩子结点为空。
python代码
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def tree2str(self, t: TreeNode) -> str:
if not t:
return ""
if not t.left and not t.right:
return str(t.val)+""
if not t.right:
return str(t.val)+"("+self.tree2str(t.left)+")"
return str(t.val)+"("+self.tree2str(t.left)+")("+self.tree2str(t.right)+")"