关于java:LeetCode104二叉树的最大深度

9次阅读

共计 877 个字符,预计需要花费 3 分钟才能阅读完成。

二叉树的最大深度

题目形容:给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的最长门路上的节点数。

阐明: 叶子节点是指没有子节点的节点。

示例阐明请见 LeetCode 官网。

起源:力扣(LeetCode)
链接:https://leetcode-cn.com/probl…
著作权归领扣网络所有。商业转载请分割官网受权,非商业转载请注明出处。

解法一:递归

首先,记录一个全局的后果 result。而后调用一个递归办法,递归办法蕴含 2 个参数,一个是以后的节点 root,一个是以后的深度 curDepth,如果 root 为空,则判断 curDepth 是否大于 result,如果大于,更新 result 为 curDepth;如果 root 不为空,则将 curDepth 加 1,而后递归调用 root 的左右子节点,直到递归实现,返回 result 即为树的最大深度。

package com.kaesar.leetcode;

public class LeetCode_104 {
    public static int result = 0;

    public static int maxDepth(TreeNode root) {maxDepth(root, 0);
        return result;
    }

    public static void maxDepth(TreeNode root, int curDepth) {if (root == null) {if (curDepth > result) {result = curDepth;}
            return;
        }
        curDepth++;
        maxDepth(root.left, curDepth);
        maxDepth(root.right, curDepth);
    }

    public static void main(String[] args) {TreeNode root = new TreeNode(1);
        root.right = new TreeNode(2);
        System.out.println(maxDepth(root));
    }
}

【每日寄语】 崎岖道路,给身边一份和煦;风雨人生,给本人一个微笑。没有什么大不了的事件,在工夫背后,都是小事。

正文完
 0