题解 | #重建二叉树#

重建二叉树

http://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6

# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param pre int整型一维数组 
# @param vin int整型一维数组 
# @return TreeNode类
#
        
class Solution:
    # 返回构造的TreeNode根节点
    def reConstructBinaryTree(self , pre: List[int], vin: List[int]) -> TreeNode:
        # write code here
        if not pre and not vin:
            return None
        root = TreeNode(pre[0])
        if set(pre)!=set(vin):
            return None        
        i = vin.index(pre[0])
        root.left = self.reConstructBinaryTree(pre[1:i+1], vin[:i])
        root.right = self.reConstructBinaryTree(pre[i+1:], vin[i+1:])
        return root
# pre = [1,2,3,5,6,4]
# vin = [5,3,6,2,4,1]
# test = Solution()
# newTree = test.reConstructBinaryTree(pre, vin)
# # 按层序遍历输出数中的某一层的值
# def PrintNodeAtlevel(treeNode,level):
#     if not treeNode or level < 0:
#         return 0
#     if level == 0:
#         print(treeNode.val)
#         return 1
#     PrintNodeAtLevel(treeNode.left,level-1)
#     PrintNodeAtlevel(treeNode.right, level-1)
    
#     # 已知树的深度按层遍历输出树的值
#     def PrintNodeByLevel(treeNode,depth):
#         for level in range(depth):
#             PrintNodeAtlevel(treeNode, level)



全部评论

相关推荐

评论
点赞
收藏
分享
牛客网
牛客企业服务