Day46: 列表转化为二叉树
2020-07-17 本文已影响0人
快乐的老周
已知列表nums,将其转化为二叉树。举例:
nums = [3,9,20,None,None,15,7],转化为二叉树后,节点3的左子节点9,右子节点20,9的左右子节点都为None,20的左子节点15,右子节点7,参考附件图片1
二叉树定义:
class TreeNode:
def init(self, x):
self.val = x
self.left = None
self.right = None
请补全下面函数:
def list_to_binarytree(nums):
pass
class TreeNode:
def init(self, x):
self.val = x
self.left = None
self.right = None
def list_to_binarytree(nums):
# def level(index):
# if index >= len(nums):# or nums[index] is None:
# return None
# print(nums[index])
# root = TreeNode(nums[index])
# root.left = level(index*2+1)
# root.right = level(index*2+2)
# return root
# return level(0)
def level(index):
if index >= len(nums):# or nums[index] is None:
return None
root = TreeNode(nums[index])
root.left = level(index*2+1)
root.right = level(index*2+2)
return root
def traverse_tree(root):
if root is not None:
print(root.val, end=' ')
if root:
if root.left is not None:
traverse_tree(root.left)
if root.right is not None:
traverse_tree(root.right)
if name == 'main':
nums = [3,9,20,None,None,15,7]
root = level(0)
traverse_tree(root)