总结树的遍历:
树的递归/深度优先搜索使用的数据结构:栈
树的层序遍历/广度优先搜索使用的数据结构:队列
解法一:树的后序遍历
class Solution {
public int maxDepth(TreeNode root) {
if(root==null){
return 0;
}
int left = maxDepth(root.left);
int right = maxDepth(root.right);
return Math.max(left,right)+1;
}
}
- 时间复杂度:O(N),需要遍历树的所有节点
- 空间复杂度:O(N),最坏情况下,树退化为链表
解法二:
class Solution {
public int maxDepth(TreeNode root) {
if(root==null){
return 0;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
int res = 0;
while(!queue.isEmpty()){
int size = queue.size();
for(int i=0;i<size;i++){
TreeNode node = queue.poll();
if(node.left!=null){
queue.add(node.left);
}
if(node.right!=null){
queue.add(node.right);
}
}
res++;
}
return res;
}
}
- 时间复杂度:O(N)
- 空间复杂度:O(N)