【日常】- maximum-depth-of-binary-tree

题目描述

求给定二叉树的最大深度。最大深度是指树的根结点到最近叶子结点的最长路径上结点的数量。

1(最初劣质版)

在这里插入图片描述

思路

遍历所有从根节点到叶子节点的路径,求最长

  1. 当栈顶左子树右子树均为空时→叶子节点:如果长度大于最长长度则记为最长长度,否则退回父节点,并进入废弃数组
  2. 当栈顶左子树不为空且左儿子不在废弃数组:左儿子入栈
  3. 当栈顶右子树不为空且右儿子不在废弃数组:右儿子入栈
  4. 当栈顶左子树右子树均不为空但均在废弃数组时:出栈
 class Solution:
    def maxDepth(self , root ):
        # write code here
        if not root:
            return 0
        pstack = [root]
        used = []
        result = 1
        while pstack:
            if pstack[-1].left==None and pstack[-1].right==None:#leaf
                if len(pstack) > result:
                    result = len(pstack)
                tmp = pstack.pop(-1)
                used.append(tmp)#del
            elif pstack[-1].left is not None and pstack[-1].left not in used:
                pstack.append(pstack[-1].left)
            elif pstack[-1].right is not None and pstack[-1].right not in used:
                pstack.append(pstack[-1].right)
            else:
                tmp = pstack.pop(-1)
                used.append(tmp)#del
        return result

2(层次遍历)

在这里插入图片描述

思路

层次遍历,返回树深度

    def run(self , root ):
        # write code here
        if not root:return 0
        level = [root]
        result = 0
        tmp = []
        while level:
            i = level.pop(0)
            if i.left:tmp.append(i.left)
            if i.right:tmp.append(i.right)
            if not level:
                level = tmp.copy()
                result += 1
                tmp = []
        return result

3(递归)

在这里插入图片描述

class Solution:
    def maxDepth(self , root ):
        # write code here
        if root is None:
            return 0
        return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值