[LeetCode] Find Bottom Left Tree Value

Posted immjc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 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.

找出树左下角的值。

利用层次遍历和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的主要内容,如果未能解决你的问题,请参考以下文章

leetcode算法: Find Bottom Left Tree Value

LeetCode - 513. Find Bottom Left Tree Value

[LeetCode] Find Bottom Left Tree Value

[leetcode] Find Bottom Left Tree Value

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

leetcode 513. Find Bottom Left Tree Value