题目如下:
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 is depth equaling 3.
这题挺简单的,就是刚睡醒醒醒脑子用的。
思路:
方法一:递归(DFS)
大概就是使用递归深度优先搜索这棵树,当节点为null时返回0,每一个节点的左右子树中取最大的再加一则为当前节点自下而上的最大路径。
代码如下:
/**
* 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) {
return helper(root);
}
public int helper(TreeNode root){
if(root == null)
return 0;
int depthOfright = 0;
int depthOfleft = 0;
depthOfright = helper(root.right);
depthOfleft = helper(root.left);
return Math.max(depthOfright,depthOfleft)+1;
}
}
方法二:迭代(BFS)
每轮迭代都把下一层的节点放入队列中,并res++,直到最底下一层。(其实和之前层序遍历差不多)
代码如下(自己懒得写了,借用了官方代码):
class Solution {
public int maxDepth(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;
}
}
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/solution/er-cha-shu-de-zui-da-shen-du-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。