给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶节点的最长路径上的节点数。
案例:
给出二叉树 [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
返回最大深度为 3 。
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.
For example:
Given binary tree [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
return its depth = 3.
个人思路:
以层次遍历二叉树的思想为基础,对每一层进行循环遍历,并在每一轮结束后记录层数增加,最终可得到该树的总层数。
代码(Java):
/**
* 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) {
Queue<TreeNode> queue=new LinkedList<TreeNode>();
if(root!=null){queue.offer(root);}
else{return 0;}
int level=0;
while(!queue.isEmpty()){
int size=queue.size();
for(int i=0;i<size;i++){
if(queue.peek().left!=null){queue.offer(queue.peek().left);}
if(queue.peek().right!=null){queue.offer(queue.peek().right);}
queue.poll();
}
level++;
}
return level;
}
}
他人思路:
用递归的方式判断左子数和右子树哪个更深,并加上当前层,即加一,可得到当前层的最大深度,直到找到空树枝后返回0,最终可得到根节点所在的最大深度。
代码(Java):
public int maxDepth(TreeNode root) {
if(root==null){
return 0;
}
return 1+Math.max(maxDepth(root.left),maxDepth(root.right));
}