第十六天|二叉树

文章介绍了使用深度优先搜索(DFS)和广度优先搜索(BFS)解决二叉树问题的两种方法,分别应用于计算最大深度和最小深度。对于最大深度,可以通过前序遍历或层次遍历来实现;最小深度则寻找左右子树中较小的深度加1。同时,文章讨论了如何计算完全二叉树的节点数量,利用满二叉树的性质进行递归计算。
摘要由CSDN通过智能技术生成

今天的题和昨天差不多,都是用dfs或者bfs去遍历

104. Maximum Depth of Binary Tree

这道题还是遍历,只不过求得是深度不是node的顺序了

Way1:

直接前序遍历:

class Solution:
    def maxDepth(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        return max(self.maxDepth(root.left),self.maxDepth(root.right))+1

Way2:

用bfs算有几层:

class Solution:
    def maxDepth(self, root: Optional[TreeNode]) -> int:
        q=deque()
        if not root:
            return 0
        res=0
        q.append(root)
        while q:
            res+=1
            for _ in range(len(q)):
                node=q.popleft()
                if node.left:
                    q.append(node.left)
                if node.right:
                    q.append(node.right)
        return res

111. Minimum Depth of Binary Tree

这道题是上一道题的变种,也一样可以用前序递归或者去做

Way1:

递归过程中找左右子树最少的然后加1为当前节点的最小的deepth

class Solution(object):
    def minDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        if not root.left:
            return self.minDepth(root.right)+1
        if not root.right:
            return self.minDepth(root.left)+1
        else:
            return min(self.minDepth(root.left),self.minDepth(root.right))+1

Way2:

还是用deque去做.这次判断要是有个node没有左右子树,则返回值

class Solution:
    def minDepth(self, root: Optional[TreeNode]) -> int:
        q=deque()
        if not root:
            return 0
        res=0
        q.append(root)
        while q:
            res+=1
            for _ in range(len(q)):
                node=q.popleft()
                if node.left:
                    q.append(node.left)
                if node.right:
                    q.append(node.right)
                if not node.left and not node.right:
                    return res
                

222. Count Complete Tree Nodes

首先完全二叉树一定包括多个小的满二叉树,可以用满二叉树的性质去做.判断满二叉树即一直递归左子树的deepth和一直递归右子树的deepth的值是相同的

Way1:

每次都算出左右的深度然后做递归

class Solution:
    def countNodes(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        l=root.left
        r=root.right
        deepth_l=0
        deepth_r=0
        while l:
            l=l.left
            deepth_l+=1
        while r:
            r=r.right
            deepth_r+=1
        if deepth_r==deepth_l:
            return (2**(deepth_l+1))-1
        return self.countNodes(root.left) + self.countNodes(root.right)+1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值