码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 513. Find Bottom Left Tree Value

时间:2017-02-18 18:16:26      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:row   result   str   ini   color   tree   tco   value   last   

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.

分析:广搜,层序遍历,保存每层的第一个值,最后的即为所求值。

 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     int findBottomLeftValue(TreeNode* root) {
13         int result = root->val;
14         queue<TreeNode *> q;
15         q.push(root);
16         TreeNode* temp;
17         while (!q.empty()) {
18             int size = q.size();
19             result = q.front()->val;
20             while (size--) {
21                 temp = q.front();
22                 q.pop();
23                 if (temp->left != NULL) q.push(temp->left);
24                 if (temp->right != NULL) q.push(temp->right);
25             }
26         }
27         return result;
28     }
29 };

 

leetcode 513. Find Bottom Left Tree Value

标签:row   result   str   ini   color   tree   tco   value   last   

原文地址:http://www.cnblogs.com/qinduanyinghua/p/6413516.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!