Leetcode[98][102] [107]python实现 二叉树

二叉树的特点

  1. 每个结点最多有两棵子树,所以二叉树中不存在度大于2的结点;
  2. 二叉树是有序的,其次序不能任意颠倒,即使树中某个结点只有一棵子树,也要区分它是左子树还是右子树。
  3. 二叉树的第 i 层上最多有2^(i-1)个结点
  4. 在一棵深度为 k 的二叉树中,最多有 2^k-1 个结点,最少有 k 个结点。

二叉树的遍历

  1. 前序遍历:若二叉树为空,则空操作返回;否则(1)访问根结点;(2)前序遍历根结点的左子树;(3)前序遍历根结点的右子树。
  2. 中序遍历:若二叉树为空,则空操作返回;否则(1)中序遍历根结点的左子树;(2)访问根结点;(3)中序遍历根结点的右子树。
  3. 后序遍历:若二叉树为空,则空操作返回;否则(1)后序遍历根结点的左子树;(2)后序遍历根结点的右子树;(3)访问根结点。
  4. 层次遍历
    各个遍历的实现 -> 假期补上

Leetcode (98) 验证二叉搜索树

题目

给定一个二叉树,判断其是否是一个有效的二叉搜索树。

假设一个二叉搜索树具有如下特征:
节点的左子树只包含小于当前节点的数。
节点的右子树只包含大于当前节点的数。
所有左子树和右子树自身必须也是二叉搜索树。

分析

利用递归来做,考虑到原函数的形参列表未包含 min 和 max 来做递归,因此额外采用了一个 valid 函数,由上至下递归,往左走则 root 的值(root.val)比 max 值(root的右上角的值)要小;往右走则 root.val 比 min 值要大(root 的左上角的值),最终到最底层出现 root 为空,结束遍历,通过。

代码

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):   # 48ms
    def isValidBST(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        return self.valid(root, None, None)
    
    def valid(self,root,min,max):
        if root == None or root.val == None:
            return True
        if(min != None and root.val <= min) or (max != None and root.val >= max):
            return False
        return self.valid(root.left,min,root.val) and self.valid(root.right,root.val,max)

学习心得

学习到python类里面调用函数需要self.xxx来指定,而不能单纯xxx
回顾了使用递归思想来解决问题

Leetcode (102) 二叉树的层次遍历

题目

给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
例如:

给定二叉树: [3,9,20,null,null,15,7],

 3
 /\
9  20
    /\
   15 7

返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]

分析

法1:32ms
bfs广度优先搜索,通过遍历的方法,设立一个res列表用于存放结果,从上至下一层层的向下更新res,直到到达底部,即root为空。
法2:32ms
使用队列,若队列不为空,记下此时队列中的结点个数temp,temp个结点出队列的同时,记录结点值,并把结点的左右子结点加入队列。

代码

法一:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def levelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        res = []
        self.f1(root, 0,res)
        return res
    def f1(self, root, depth, res):
        if root == None:
            return
        if len(res) < depth+1:               #建立该层的空元素数组
            res.append([])
        res[depth].append(root.val)         #将层中元素加入该数组中
        self.f1(root.left, depth+1, res)
        self.f1(root.right, depth+1, res)

法二:

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

Leetcode (107) 二叉树的层次遍历 II

给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)

例如:
给定二叉树 [3,9,20,null,null,15,7]

 3
 /\
9  20
    /\
   15 7

返回其自底向上的层次遍历为:

[
[15,7],
[9,20],
[3]
]

分析

32ms
与上题 Leetcode (102)法2类似,只是最后加入res的时候从前边加入;也可使用reverse来翻转list

代码

class Solution(object):
    def levelOrderBottom(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 = [templist] + res
        return res

部分参考自:
https://blog.csdn.net/IT_job/article/details/80496324
https://blog.csdn.net/weixin_40314737/article/details/80942856
https://blog.csdn.net/weixin_44154393/article/details/85148623

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值