给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
思路:
方法1:深度优先搜索
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;
}
}
时间复杂度:O(n)
空间复杂度:O(height)