【LeetCode】513. Find Bottom Left Tree Value-查找二叉树最左下角元素

一、描述:

二、思路:

使用队列Queue按序(从左至右)存储每一层的结点,若不是最后一层,则在添加完下一层全部结点后,将上一层结点全部移除,直到最后一层,此时获取队首结点,即为所求;

如何判断当前层是不是最后一层,可以通过二叉树的深度来控制;

故该思路需要两个方法,方法一获取深度,方法二进行每一层结点的压入和移除,用到BFS。

注:代码略长,只是第一次想到的解法

三、代码:

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public int findBottomLeftValue(TreeNode root) {
12         Queue<TreeNode> queue = new LinkedList<TreeNode>();
13         int depth = depth(root);//获得二叉树深度
14         queue.offer(root);//压入首结点
15         while(depth>1){
16             int size = queue.size();//当前Queue中结点个数
17             for(int i=0;i<size;i++){
18                 TreeNode node = queue.remove();//若不是最后一层,则循环移除Queue中的上一层结点
19                 if(node.left!=null){
20                     queue.offer(node.left);
21                 }
22                 if(node.right!=null){
23                     queue.offer(node.right);
24                 }
25             }
26             depth--;
27         }
28         TreeNode result = queue.peek();
29         if(result!=null){
30             return result.val;
31         }
32         return 0;
33     }
34     
35     //求二叉树深度
36     public int depth(TreeNode root){
37         if(root==null){
38             return 0;
39         }
40         if(root.left==null && root.right==null){
41             return 1;
42         }
43         int left = depth(root.left);
44         int right = depth(root.right);
45         return  left<right?right+1:left+1;
46     }
47 }

 

转载于:https://www.cnblogs.com/WalkerSteve/p/6608151.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值