LeetCode 104. 二叉树的最大深度(包含回溯过程图)

本文详细介绍了如何使用层序遍历、后序遍历和前序遍历来解决LeetCode上的二叉树最大深度问题。通过示例代码展示了三种不同遍历方法的实现,并解释了每种方法的思路。对于层序遍历,每次遍历完一层记录深度;后序遍历通过递归计算左右子树深度取最大值加1;前序遍历则在递归过程中不断更新最大深度。
摘要由CSDN通过智能技术生成

层序遍历的应用:
移步->LeetCode 104. 二叉树的最大深度
移步->LeetCode 102. 二叉树的层序遍历
移步->LeetCode 226. 翻转二叉树
移步-LeetCode 515. 在每个树行中找最大值

题目链接:104. 二叉树的最大深度

标准的层序遍历,每次遍历完一层记录深度即可

class Solution {
    public int maxDepth(TreeNode root) {
        Queue<TreeNode> que = new LinkedList<TreeNode>();
        int depth = 0;
        if(root == null) return depth;
        que.offer(root);
        
        while(!que.isEmpty()){
            int len = que.size();
            while(len>0){
                TreeNode curNode = que.poll();
                if(curNode.left!=null) que.offer(curNode.left);
                if(curNode.right!=null) que.offer(curNode.right);
                len--;
            }
            depth++;
        }
        return depth;
    }
}

后序遍历

这里要搞清楚为什么可以使用后序遍历,因为这里要求的根结点的最大深度,就是树的高度。所以可以使用后序遍历,遍历到根结点。代码很简洁。

class solution {
    /**
     * 递归法
     */
    public int maxdepth(treenode root) {
        if (root == null) {
            return 0;
        }
        int leftdepth = maxdepth(root.left);
        int rightdepth = maxdepth(root.right);
        return math.max(leftdepth, rightdepth) + 1;
    }
}

前序遍历

使用前序遍历实现真正的求最大深度。(为什么说是真正的呢?因为深度就是由根到叶子节点计算的,所以前序遍历是最合适的)。这种做法默认root的深度为1,并且每个节点都有一个深度。每次递归都更新一次最大深度。

class Solution {
    public int result = 0;
    public int maxDepth(TreeNode root) {
        if(root == null) return result;
        getdepth(root,1);
        return result;
    }
    void getdepth(TreeNode root,int depth){
        result = depth > result?depth:result;
        if(root.left == null && root.right == null) return;	//结束当前结点的递归

        if(root.left!=null){
            depth++;
            getdepth(root.left,depth);
            depth--;
        }
        if(root.right!=null){
            depth++;
            getdepth(root.right,depth);
            depth--;
        }
    }
}

回溯过程图

为了理解这里return的用法和整个遍历过程,我们画图看看。
在这里插入图片描述
完美!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

疯狂java杰尼龟

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

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

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

打赏作者

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

抵扣说明:

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

余额充值