LeetCode——513 找树左下角的值(JAVA)

给定一个二叉树,在树的最后一行找到最左边的值。

示例 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;
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值