算法课 第四周 Find Bottom Left Tree Value

Given a binary tree, find the leftmost value in the last row of the tree.

Example 1:

Input:

    2
   / \
  1   3

Output:
1

Example 2: 

Input:

        1
       / \
      2   3
     /   / \
    4   5   6
       /
      7

Output:
7

Note: You may assume the tree (i.e., the given root node) is not NULL.

Subscribe to see which companies asked this question.



题目分析:

1、根据题干,题目要求计算一颗树的底部(左侧)的值,也就是找到深度最大的叶节点,若存在多个,则取最左边的。

2、BFS算法:BFS在本题中显然比DFS更适合,因为它不需要DFS中单独记录之前的判断信息,判断过程也更加简单。具体实现由Queue完成,BFS也可以理解为层序遍历,我们只需要将常规的层序遍历稍加改动,即每层从右端开始push即可,这样整个BFS完成的时候最后一个元素即为所求的结点,返回其val即可。此题采用BFS。

代码

[cpp]  view plain  copy
  1. /** 
  2.  * Definition for a binary tree node. 
  3.  * struct TreeNode { 
  4.  *     int val; 
  5.  *     TreeNode *left; 
  6.  *     TreeNode *right; 
  7.  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} 
  8.  * }; 
  9.  */  
  10. #include<queue>   
  11.    
  12. class Solution {  
  13. public:  
  14.     int findBottomLeftValue(TreeNode* root) {  
  15.         queue<TreeNode*> Q;  
  16.         Q.push(root);  
  17.         int ans;  
  18.         while(Q.size()){  
  19.             if(Q.front()->right != NULL)  
  20.                 Q.push(Q.front()->right);  
  21.             if(Q.front()->left != NULL)  
  22.                 Q.push(Q.front()->left);  
  23.             ans = Q.front()->val;  
  24.             Q.pop();  
  25.         }   
  26.         return ans;   
  27.     }  
  28. };  



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值