• [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

     Using dfs to solve this problem.

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        int findBottomLeftValue(TreeNode* root) {
            int val = 0;
            int depth = 1;
            int height = 0;
            dfs(root, depth, height, val);
            return val;
        }
        
        void dfs(TreeNode* node, int depth, int& height, int& val) {
            if (node == nullptr)
                return;
            if (depth > height) {
                val = node->val;
                height = depth;
            }
            dfs(node->left, depth + 1, height, val);
            dfs(node->right, depth + 1, height, val);
        }
    };
    // 13 ms
  • 相关阅读:
    vue集成百度UEditor富文本编辑器
    HTTPS访问站点,出现证书问题解决(转载) 规格严格
    JSSE 提供的 动态 debug 追踪模式 规格严格
    javax.net.debug 规格严格
    Oralce null 规格严格
    pipe 规格严格
    (总结)ibatis 动态传入表名和列名 规格严格
    垃圾回收算法简介 规格严格
    转载(正则表达式的分类) 规格严格
    长度为0的数组 规格严格
  • 原文地址:https://www.cnblogs.com/immjc/p/8316884.html
Copyright © 2020-2023  润新知