[leetCode]104.二叉树的最大深度
解法一 递归
/**
* 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;
else{
int leftHeight = maxDepth(root.left);
int rightHeight = maxDepth(root.right);
return Math.max(leftHeight,rightHeight)+1;
}
}
}
解法二 广优先搜索
首先加入根结点,每次弹出一个结点,加入左右子节点并跟新每个结点的深度,使用一个遍历不断更新最大深度
/**
* 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) {
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 currentMaxH = current.getValue();
if(root != null){
depth = Math.max(currentMaxH, depth);
stack.add(new Pair(root.left,depth + 1));
stack.add(new Pair(root.right,depth + 1));
}
}
return depth;
}
}
每次往栈中添加一层结点,遍历取出该层结点添加下一层非空结点,每层遍历完成,层级+1
/**
* 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> stack = new LinkedList<>();
stack.add(root);
int level = 0;
while(!stack.isEmpty()){
int levelSize = stack.size();//每一层的节点数
for(int i = 0; i < levelSize; i++){//每次弹出一层结点,添加下一层结点
root = stack.poll();
if(root.left!=null){
stack.add(root.left);
}
if(root.right!=null){
stack.add(root.right);
}
}
level++;
}
return level;
}
}