1 思路
使用递归创建二叉树,每个节点最多有两个子节点,以索引去从列表中取子节点的值,i为根节点,左子节点的值为2×i+1,右子节点的值为2×i+2。
2 python实现
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def createTree(root,rt,i):
if i <len(rt):
if not rt[i]:
return None
else:
root = TreeNode(rt[i])
root.left = createTree(root.left,rt,2*i+1)
root.right = createTree(root.right,rt,2*i+2)
return root
return root
root_list = [3,9,20,None,None,15,7]
root = TreeNode(-1)
root = createTree(root,root_list,0)