层序遍历(BFS)
class Solution {
public int maxDepth(TreeNode root) {
if(root == null)
return 0;
List<TreeNode> queue = new LinkedList<>() {{ add(root); }}, tmp;
int res = 0;
while(!queue.isEmpty()) {
tmp = new LinkedList<>();
for(TreeNode node : queue) {
if(node.left != null)
tmp.add(node.left);
if(node.right != null)
tmp.add(node.right);
}
queue = tmp;
res++;
}
return res;
}
}
后序遍历(DFS)
class Solution {
public int maxDepth(TreeNode root) {
if(root == null) return 0;
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
}
转载于:Leecode