题目描述:
给定一个二叉树的 根节点 root
,请找出该二叉树的 最底层 最左边 节点的值。
假设二叉树中至少有一个节点。
思路:
1)层序遍历
2)递归中动态更新 最大深度,不用单独计算!
代码:
1)手写层序遍历:效率很差
class Solution {
public int findBottomLeftValue(TreeNode root) {
//层序遍历找到最后一层
List<TreeNode> temp = new ArrayList<>();//记录每一层的节点
Queue<TreeNode> queue = new LinkedList<>();
if(root == null) return 0;
queue.offer(root);
while(!queue.isEmpty()){
temp = new ArrayList<>();//每次循环都是一个新的
int size = queue.size();
for(int i = 0;i < size;i++){
TreeNode node = queue.poll();
temp.add(node);
if(node.left != null) queue.offer(node.left);
if(node.right != null) queue.offer(node.right);
}
}
//此时的list中是最后一个
return temp.get(0).val;
}
}
2) 优化:不需要列表的操作,每次while进去就拿 其peek的值
class Solution {
public int findBottomLeftValue(TreeNode root) {
//层序遍历找到最后一层
Queue<TreeNode> queue = new LinkedList<>();
if(root == null) return 0;
queue.offer(root);
int res = Integer.MIN_VALUE;
while(!queue.isEmpty()){
res = queue.peek().val;
int size = queue.size();
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);
}
}
//此时的list中是最后一个
return res;
}
}
另一种优化方式:
class Solution {
public int findBottomLeftValue(TreeNode root) {
//层序遍历找到最后一层
Queue<TreeNode> queue = new LinkedList<>();
if(root == null) return 0;
queue.offer(root);
//一直循环
//先加右子树,拿到的就是最后一个节点!
//前面后序遍历做题,按照中右左的方式添加后反转,一样的道理
while(!queue.isEmpty()){
root = queue.poll();
if(root.right != null) queue.offer(root.right);
if(root.left != null) queue.offer(root.left);
}
//此时的list中是最后一个
return root.val;
}
}
3)递归:
class Solution {
int res = 0;
int maxDepth = -1;
public int findBottomLeftValue(TreeNode root) {
//DFS:深度优先
dfs(root,0);
//递归改变了res的值
return res;
}
//第一次到该层,肯定比原来的最大深度大,更新;
void dfs(TreeNode root,int depth){
//走到了底
if(root == null) return;
if(depth > maxDepth){
res = root.val;
maxDepth = depth;
}
//按照从左往右的顺序
dfs(root.left,depth + 1);
dfs(root.right,depth + 1);
}
}