美文网首页
Day46: 列表转化为二叉树

Day46: 列表转化为二叉树

作者: 快乐的老周 | 来源:发表于2020-07-17 11:02 被阅读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)

    相关文章

      网友评论

          本文标题:Day46: 列表转化为二叉树

          本文链接:https://www.haomeiwen.com/subject/swfvhktx.html