python编程——004二叉树、遍历到层次遍历leetcode98、102、107

一、二叉树
二叉树是树的特殊一种,具有如下特点:1、每个结点最多有两颗子树,结点的度最大为2。2、左子树和右子树是有顺序的,次序不能颠倒。3、即使某结点只有一个子树,也要区分左右子树。
二叉树性质:
1、在非空二叉树的i层上,至多有2i-1个节点(i>=1)。通过归纳法论证。
2、在深度为K的二叉树上最多有2k-1个结点(k>=1)。通过归纳法论证。
3、对于任何一棵非空的二叉树,如果叶节点个数为n0,度数为2的节点个数为n2,则有: n0 = n2 + 1在一棵二叉树中,除了叶子结点(度为0)之外,就剩下度为2(n2)和1(n1)的结点了。则树的结点总数为T = n0+n1+n2;在二叉树中结点总数为T,而连线数为T-1.所以有:n0+n1+n2-1 = 2*n2 +n1;最后得到n0 = n2+1;
二、练习
leetcode98
1)题目
在这里插入图片描述

2)答案

class Solution(object):
    pre=None
    def isValidBST(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        
        if root is None: 
            return True
        Bool= self.isValidBST(root.left)
        
        if self.pre!=None:
            Bool=Bool and (self.pre.val<root.val)
        
        self.pre=root
        
        Bool=Bool and self.isValidBST(root.right)
        return Bool


3)分析
为Solution类添加pre数据成员,在中序遍历二叉搜索树的过程中,pre用来指向当前节点的前驱节点。
注意:pre不能放在isValidBST函数的内部。如果将pre放在isValidBST函数的内部,则每一次递归调用isValidBST函数的时候,pre都将重新赋值为None。实际上,在每一次递归调用时,我们需要的是上一次调用结束时pre的值’’’

leetcode102
1)题目
在这里插入图片描述

2)答案

class Solution(object):
    def levelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        queue = [root]
        res = []
        if not root:
            return []
        while queue:
            templist = []
            templen =len(queue)
            for i in range(templen):                
                temp = queue.pop(0)
                templist.append(temp.val)
                if temp.left:
                    queue.append(temp.left)
                if temp.right:
                    queue.append(temp.right)
            res.append(templist)
        return res

在这里插入图片描述
3)分析
用队列实现:root为空,则返回空表,队列不为空,记下此时队列中的结点个数temp,temp个结点出队列的同时,记录结点值,并把结点的左右子结点加入队列

leetcode107
1)题目
在这里插入图片描述

2)答案

class Solution(object):
    def levelOrderBottom(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        if not root:
            return []
        queue=[root]
        res=[]
        while queue:
            nodes=[]
            node_values=[]
            for node in queue:
                if node.left:
                    nodes.append(node.left)
                if node.right:
                    nodes.append(node.right)
                node_values+=[node.val]
            res=[node_values]+res
            queue=nodes
        return res

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值