public int maxDepth(TreeNode root) {
if(root == null)
return 0;
else {
int leftHeight = maxDepth(root.left);
int rightHeight = maxDepth(root.right);
return Math.max(leftHeight,rightHeight)+1;
}
}
迭代
public static int maxDepth1(TreeNode root) {//10ms
Queue<Pair<TreeNode,Integer>> stack = new LinkedList<>();
if(root != null)
stack.add(new Pair<>(root,1));
int depth = 0;
while (!stack.isEmpty()){
Pair<TreeNode, Integer> current = stack.poll();
root = current.getKey();
int currentDepth = current.getValue();
if(root!=null){
depth = Math.max(depth,currentDepth);
stack.add(new Pair<>(root.left,currentDepth+1));
stack.add(new Pair<>(root.right,currentDepth+1));
}
}
return depth;
}