题目:
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.
此题类似二叉树最小深度。
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.*;
public class Solution {
public int maxDepth(TreeNode root) {
if(root==null)
return 0;
if(root.left==null&&root.right==null)
return 1;
方法一:递归
/* if(root.left==null)
return maxDepth(root.right)+1;
if(root.right==null)
return maxDepth(root.left)+1;
int left=maxDepth(root.left);
int right=maxDepth(root.right);
return (left>right)?(left+1):(right+1);
*/
//方法二:层序遍历结束,每一层level加一
Queue<TreeNode> q=new LinkedList<>();
q.add(root);
int level=0;
while(!q.isEmpty()){
int size=q.size();
level++;
for(int i=0;i<size;i++){
TreeNode node=q.poll();
if(node.left!=null)
q.add(node.left);
if(node.right!=null)
q.add(node.right);
}
}
return level;
}
}