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.
思路:在求樹的最小深度算法上稍作改動就可實現找到最大深度。AC代碼:
import java.util.ArrayList;
public class Solution {
public int maxDepth(TreeNode root) {
if( root == null ) return 0;
ArrayList<TreeNode> lastLevel = new ArrayList<TreeNode>();
int count = 1;
lastLevel.add(root);
while( !lastLevel.isEmpty() ){
ArrayList<TreeNode> nextLevel = new ArrayList<TreeNode>();
for( TreeNode treenode:lastLevel ){
if( treenode.left != null ) nextLevel.add(treenode.left);
if( treenode.right != null ) nextLevel.add(treenode.right);
}
if( nextLevel.isEmpty() ) break;
count++;
lastLevel = new ArrayList<TreeNode>(nextLevel);
}
return count;
}
}