给定一个二叉树的 根节点 root,请找出该二叉树的 最底层 最左边 节点的值。
假设二叉树中至少有一个节点。
示例 1:
输入: root = [2,1,3]
输出: 1
示例 2:
输入: [1,2,3,4,null,5,6,null,null,7]
输出: 7
提示:
二叉树的节点个数的范围是 [1,104]
-231 <= Node.val <= 231 - 1
/**
* Definition for a binary tree node.
* 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;
* }
* }
*/
class Solution {
/**
层序遍历,取每层第一个值即可
*/
public int findBottomLeftValue(TreeNode root) {
Deque<TreeNode> q = new LinkedList<>();
q.addLast(root);
int res = -1;
while (!q.isEmpty()) {
int size = q.size();
res = q.peekFirst().val;
while (size-- > 0) {
TreeNode t = q.pollFirst();
if (t.left != null) q.addLast(t.left);
if (t.right != null) q.addLast(t.right);
}
}
return res;
}
}