[LeetCode] 104. Maximum Depth of Binary Tree ☆(二叉树的最大深度)

时间:2023-03-09 15:09:40
[LeetCode] 104. Maximum Depth of Binary Tree ☆(二叉树的最大深度)

描述

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Note: A leaf is a node with no children.

Example:

Given binary tree [3,9,20,null,null,15,7],

    3
/ \
9 20
/ \
15 7

return its depth = 3.

解析

深度优先搜索DFS

简单的递归。递归条件是,它的最大深度是它左子树的最大深度和右子树最大深度中较大的那个加1。基础条件是,当遇到空节点时,返回深度为0。该递归的实质是深度优先搜索。

层序遍历

一层的节点,依次入队列,依次出队列。

代码

深度优先搜索DFS

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
if (null == root) {
return 0;
}
int leftMax = maxDepth(root.left);
int rightMax = maxDepth(root.right);
return Math.max(leftMax, rightMax) + 1;
}
}

层序遍历

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
if (null == root) {
return 0;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int nodeSum = 0;
while (!queue.isEmpty()) {
nodeSum++;
int stackSize = queue.size();
for (int i = 0; i < stackSize; i++) {
TreeNode curNode = queue.poll();
if (curNode.left != null) {
queue.offer(curNode.left);
}
if (curNode.right != null) {
queue.offer(curNode.right);
}
}
}
return nodeSum;
}
}