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

[LeetCode] Find Bottom Left Tree Value

时间:2018-01-19 15:37:07      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:pos   push   value   nullptr   ptr   example   root   color   find   

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.

找出树左下角的值。

利用层次遍历和hashmap的key唯一性。

层次遍历二叉树,用hashmap来存储每一层的第一个节点,key为层数,value为节点值。

最后返回hashmap值为层数的那个value即可

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
static int layer = 0;
class Solution {
public:
    int findBottomLeftValue(TreeNode* root) {
        queue<TreeNode*> q;
        q.push(root);
        unordered_map<int, TreeNode*> m;
        while (!q.empty()) {
            int n = q.size();
            layer++;
            for (int i = 0; i < n; i++) {
                TreeNode* curNode = q.front();
                q.pop();
                m.insert({layer, curNode});
                if (curNode->left != nullptr)
                    q.push(curNode->left);
                if (curNode->right != nullptr)
                    q.push(curNode->right);
            }
        }
        return m[layer]->val;
    }
};
// 13 ms

 

[LeetCode] Find Bottom Left Tree Value

标签:pos   push   value   nullptr   ptr   example   root   color   find   

原文地址:https://www.cnblogs.com/immjc/p/8316884.html

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