给定一个二叉树,在树的最后一行找到最左边的值。
示例 1:
输入:
2
/ \
1 3
输出:
1
示例 2:
输入:
1
/ \
2 3
/ / \
4 5 6
/
7
输出:
7
注意: 您可以假设树(即给定的根节点)不为 NULL。
思路
找到最后一行最左边结点的值,其实就是最后一层第一个结点的值,所以用BFS搜索即可。
具体做法就是:每当搜索到发现当前结点的层次与上一层结点层次不一样时(说明此时的结点是下一层的第一个结点),更新bottomLeft
为当前结点。最后,对只有一个根结点的情况进行特判就可以了。
代码
public class Solution {
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 Node{
TreeNode node;
int layer;
Node() {}
Node(TreeNode node, int layer){
this.node = node;
this.layer = layer;
}
}
Queue<Node> queue = new LinkedList<Node>();
Node bottomLeft = new Node();
public void bfs(Node root) {
queue.offer(root);
int nowLayer = root.layer;
while(queue.isEmpty()==false) {
Node topNode = queue.poll();
if(topNode.layer==1&&topNode.node.left==null&&topNode.node.right==null) {//如果该树只有一个根结点
bottomLeft = topNode;
}
if(topNode.layer>nowLayer) {//如果是新一层的第一个结点
nowLayer = topNode.layer;
bottomLeft = topNode;
}
if(topNode.node.left!=null) {
Node lchild = new Node(topNode.node.left, topNode.layer+1);
queue.offer(lchild);
}
if(topNode.node.right!=null) {
Node rchild = new Node(topNode.node.right, topNode.layer+1);
queue.offer(rchild);
}
}
}
public int findBottomLeftValue(TreeNode root) {
Node rootNode = new Node(root, 1);
bfs(rootNode);
return bottomLeft.node.val;
}
}