注意事项:
- 建树是遍历建树的,但是所给的list不一定是先序、后序、中序的结构,而是正常的广度优先遍历结构,这是可以使用2*i+1表示左孩子,2*i+2表示右孩子;或者使用Bfs遍历建树;
- 递归建树的时候,一定要注意,边界return的内容是什么,会不会对下次return产生影响;以及最后是否需要return root;同时注意整个减少的要求:比如,肯定list不能越界才对。
class TreeNode:
def __init__(self, val: int):
self.val = val
self.left = None
self.right = None
node = TreeNode
tree = [3, 5, 1, 6, 2, 0, 8, '+', '+', 7, 4]
def build(root, tree, i):
if i < len(tree):
if tree[i] == '+':
return None
root = TreeNode(tree[i])
root.left = build(root.left, tree, 2 * i + 1)
root.right = build(root.right, tree, 2 * i + 2)
return root # 这个return root还是十分关键的 不然被返回None以后怎么往上返回呢
root = build(None, tree, 0)
print(root)
def xian(root):
if not root: return None # 但是这个地方就是可以的,因为他是return None之后接着对return的结果进行判断
print(root.val)
xian(root.left)
xian(root.right)
xian(root)