0513. Find Bottom Left Tree Value #
题目 #
给定一棵二叉树的 根节点 root
,找出该二叉树的 最底层 最左边 节点的值。
假定二叉树至少有一个节点。
思路 #
- 层数遍历
代码 #
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) {
int ans = root.val;
Queue<TreeNode> queue = new Linkedlist<>();
queue.offer(root);
while (queue.size() != 0) {
int layerSize = queue.size();
ans = queue.peek().val;
for (int i = 0; i < layerSize; i++) {
TreeNode node = queue.poll();
if (node.left != null) queue.offer(node.left);
if (node.right != null) queue.offer(node.right);
}
}
return ans;
}
}