剑指offer python 重建二叉树 两种解法 牛客网

版权声明:本文由lianyhai编写,不得用于商业用途,其他用途请随便。如果非要用做商业用途请给我微信打一下钱谢谢!哈哈哈哈 https://blog.csdn.net/qq_36303521/article/details/88134351
# -*- coding:utf-8 -*-
#class TreeNode:
#    def __init__(self, x):
#        self.val = x
#        self.left = None
#        self.right = None
class Solution:
    # 返回构造的TreeNode根节点
    def reConstructBinaryTree(self, pre, tin):
        # write code here
        if len(pre)==0:
            return None
        else:
            pos = tin.index(pre[0])
        tree = TreeNode(pre[0])
        tree.left=self.reConstructBinaryTree(pre[1:pos+1],tin[:pos])
        tree.right=self.reConstructBinaryTree(pre[pos+1:],tin[pos+1:])
        return tree

第一种解法:
第一,检查长度是否为零
第二,计算root的位置
第三,创建树的实例,添加左右叶子。

第二种差不多,但是比较简洁

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def reConstructBinaryTree(self, pre, tin):
        if not pre or not tin:
            return None
        root = TreeNode(pre.pop(0))
        index = tin.index(root.val)
        root.left = self.reConstructBinaryTree(pre, tin[:index])
        root.right = self.reConstructBinaryTree(pre, tin[index + 1:])
        return root

学到的知识:
函数还有写完就可以再次调用自己,用self.fun()
在另外一个list里面找数值一样的索引 y.index(x[])
检查是否为空集可以这样

if not x or not y:
    return None

猜你喜欢

转载自blog.csdn.net/qq_36303521/article/details/88134351
今日推荐