题目描述
Given a binary tree, find the leftmost value in the last row of the tree.



方法思路
Appraoch1:
简单粗暴的方法
class Solution {
//Runtime: 3 ms, faster than 95.43%
//Memory Usage: 39.8 MB, less than 11.18%
int depth, ans;
public int findBottomLeftValue(TreeNode root) {
depth = 0;
ans = root.val;
if(root.left == null && root.right == null)
return ans;
find_Helper(root, 0);
return ans;
}
public void find_Helper(TreeNode root, int sub_depth){
if(root == null) return;
if(root.left != null && root.left.left == null && root.left.right == null){
if((sub_depth + 1) > depth){
depth = sub_depth + 1;
ans = root.left.val;
}
}
if(root.right != null && root.right.left == null && root.right.right == null){
if((sub_depth + 1) > depth){
depth = sub_depth;
ans = root.right.val;
}
}
find_Helper(root.left, sub_depth + 1);
find_Helper(root.right, sub_depth + 1);
}
}
Appraoch2:
利用队列的数据结构,进行从右至左的层序遍历
class Solution {
//Runtime: 4 ms, faster than 64.10%
//Memory Usage: 40.2 MB, less than 5.30%
public int findBottomLeftValue(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
root = queue.poll();
if (root.right != null)
queue.add(root.right);
if (root.left != null)
queue.add(root.left);
}
return root.val;
}
}
给定一棵二叉树,找到最后一层最左边的节点的值。方法包括直接层序遍历和利用队列实现从右到左的层序遍历。

被折叠的 条评论
为什么被折叠?



