[LeetCode]513 Find Bottom Left Tree Value(BFS)

题目链接:https://leetcode.com/problems/find-bottom-left-tree-value/?tab=Description

题意:找到二叉树里最底下的最靠左的叶子节点的值。

看到input的时候吓哭了,以为是要处理这种输入。看到代码填空部分才缓过来…

直接bfs,遇到更深的就更新,每次都让最左的先入队列。就能保证每次更新到的答案都是最左的。

 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 class Solution {
11 public:
12   typedef pti pair<TreeNode*, int>;
13   int findBottomLeftValue(TreeNode* root) {
14     queue<pti> q;
15     q.push(pti(root, 0));
16     pti ret(NULL, -1);
17     while(!q.empty()) {
18         pti f = q.front(); q.pop();
19         if(f.first->left) q.push(pti(f.first->left, f.second+1));
20         if(f.first->right) q.push(pti(f.first->right, f.second+1));
21         if(ret.second < f.second) {
22             ret = f;
23         }
24     }
25     return ret;
26   }
27 };

 

posted @ 2017-03-10 14:19  Kirai  阅读(280)  评论(0编辑  收藏  举报