给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
递归找出左右子树中高度最大的树
class Solution {
public int maxDepth(TreeNode root) {
if(root == null) {
return 0;
}
return 1+Math.max(maxDepth(root.right),maxDepth(root.left));
}
}
复杂度分析
时间复杂度:我们每个结点只访问一次,因此时间复杂度为 O(N), 其中 N 是结点的数量。
空间复杂度:在最糟糕的情况下,树是完全不平衡的,例如每个结点只剩下左子结点,递归将会被调用 N 次(树的高度),因此保持调用栈的存储将是 O(N)。但在最好的情况下(树是完全平衡的),树的高度将是log(N)。因此,在这种情况下的空间复杂度将是 O(log(N))。
第二中 leecode 使用队列做的
class Solution {
public int maxDepth(TreeNode root) {
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 current_depth = current.getValue();
if (root != null) {
depth = Math.max(depth, current_depth);
stack.add(new Pair(root.left, current_depth + 1));
stack.add(new Pair(root.right, current_depth + 1));
}
}
return depth;
}
}
复杂度分析
时间复杂度:O(N).
空间复杂度:O(N).