·leetcode- 104-二叉树的最大深度
给定一个二叉树 root
,返回其最大深度。
二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。
示例 1:
输入:root = [3,9,20,null,null,15,7] 输出:3
示例 2:
输入:root = [1,null,2] 输出:2
·遍历方法有三个:
迭代法最简单(遍历左数和右数,取最大)
基于广度优先算法,需要用到队列
基于深度优先算法,需要用到栈。
·Java代码
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
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;
}
public int maxDepth1(TreeNode root){
if(root == null) return 0;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int depth = 0;
while(!queue.isEmpty()){
int size = queue.size();
depth ++;
for(int i = 0; i < size ; i ++){
TreeNode node = queue.poll();
if(node.left != null) queue.offer(node.left);
if(node.right != null) queue.offer(node.right);
}
}
return depth;
}
public int maxDepth2(TreeNode root){
if(root == null) return 0;
Stack<TreeNode> stack = new Stack<TreeNode>();
Stack<Integer> depths = new Stack<Integer>();
int maxDepth = 0;
stack.push(root);
depths.push(1);
while(! stack.isEmpty()){
TreeNode node = stack.pop();
int depth = depths.pop();
if(node != null) maxDepth = Math.max(maxDepth, depth);
if(node.left != null) {
stack.push(node.left);
depths.push(depth + 1);
}
if(node.right != null){
stack.push(node.right);
depths.push(depth + 1);
}
}
return maxDepth;
}
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
}