剑指 offer 55 二叉树的深度
代码01
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
if(root==null){
return 0;
}
return Math.max(maxDepth(root.left),maxDepth(root.right))+1;
}
}
时间复杂度
O
(
n
)
O(n)
O(n),
n
n
n是树的节点数量,计算树的深度需要遍历所有节点。
空间复杂度
O
(
n
)
O(n)
O(n),最差情况下(树退化为链表时),递归深度可达到
n
n
n。
层序遍历,广度优先
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
if(root==null){
return 0;
}
Queue<TreeNode> queue = new LinkedList<>();
int res = 0;
TreeNode p;
queue.add(root);
while(!queue.isEmpty()){
Queue<TreeNode> tmp = new LinkedList<>();
while(!queue.isEmpty()){
p = queue.poll();
if(p.left!=null){
tmp.add(p.left);
}
if(p.right!=null){
tmp.add(p.right);
}
}
res++;
queue.addAll(tmp);
}
return res;
}
}
时间复杂度
O
(
n
)
O(n)
O(n),
n
n
n是树的节点数量,计算树的深度需要遍历所有节点。
空间复杂度
O
(
n
)
O(n)
O(n),最差情况下(树退化为链表时),递归深度可达到
n
n
n。