PisecesPeng / PisecesPeng.record.me

:beach_umbrella: All things are difficult before they are easy
MIT License
3 stars 1 forks source link

二叉树的最大深度 #30

Closed PisecesPeng closed 3 years ago

PisecesPeng commented 3 years ago

二叉树的最大深度

给定一个二叉树, 找出其最大深度.
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数.

说明: 叶子节点是指没有子节点的节点.

示例:

给定二叉树[3,9,20,null,null,15,7]

    3
   / \
  9  20
    /  \
   15   7

返回它的最大深度3.


题目地址: https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/

PisecesPeng commented 3 years ago

解题思路

代码

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() { }
    TreeNode(int val) { this.val = val; }
}
public static int func(TreeNode root) {
    if (null == root) return 0;
    return Math.max(func(root.left) + 1, func(root.right) + 1);
}
PisecesPeng commented 3 years ago

LeetCode题解

解题思路

代码

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() { }
    TreeNode(int val) { this.val = val; }
}
public static int func(TreeNode root) {
    if (root == null) {
        return 0;
    }
    Queue<TreeNode> queue = new LinkedList<TreeNode>();
    queue.offer(root);
    int ans = 0;
    while (!queue.isEmpty()) {
        int size = queue.size();
        while (size > 0) {
            TreeNode node = queue.poll();
            if (node.left != null) {
                queue.offer(node.left);
            }
            if (node.right != null) {
                queue.offer(node.right);
            }
            size--;
        }
        ans++;
    }
    return ans;
}