LeetCode:104. 二叉树的最大深度(python3,javaScript)

104. 二叉树的最大深度

在这里插入图片描述

python3

法1:递归法

思路:
在这里插入图片描述

class Solution:
    def maxDepth(self, root):
        #递归法
        # if root is None:
        #     return 0
        # else:
        #     lh = self.maxDepth(root.left)
        #     rh = self.maxDepth(root.right)
        #     return max(lh,rh) + 1

法2:迭代法

思路:

生成一个列表用来存放每一层的内容,通过遍历一层然后加一,

class Solution:
    def maxDepth(self, root):
        #迭代法
        if not root:
            return 0
        queue,res = [root],0
        while queue:
            l = len(queue)
            for i in range(l):
                node = queue.pop(0)
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
            res += 1
        return res

JavaScript

法1:递归法

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var maxDepth = function(root) {
    // 递归法
     if(!root){
         return 0
     }
     else{
         const lh = maxDepth(root.left);
         const rh = maxDepth(root.right);
         return Math.max(lh,rh) + 1
     }

};

法2:迭代法

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var maxDepth = function(root) {
    // 迭代法
    if (root == null) return 0;
    var queue = [root];
    let depth = 1;
    while (queue.length){
        const levelSize = queue.length;          
        for (let i = 0; i < levelSize; i++) {    
            const cur = queue.shift();            
            if (cur.left) queue.push(cur.left);
            if (cur.right) queue.push(cur.right); 
        }
        if (queue.length) depth++;
    }
    return depth;

};
  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

南岸青栀*

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值