题目描述
给定一个二叉树,在树的最后一行找到最左边的值。
Sample Code 1
class Solution {
private int res;
private int max = Integer.MIN_VALUE;
public int findBottomLeftValue(TreeNode root) {
dfs(root, 0);
return res;
}
private void dfs(TreeNode root, int depth) {
if(root == null) return;
if(root.left == null && root.right == null) {
if(depth > max) {
max = depth;
res = root.val;
}
}
dfs(root.left, depth+1);
dfs(root.right, depth+1);
}
}
Sample Code 2
class Solution {
public int findBottomLeftValue(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
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);
}
return root.val;
}
}