Find Bottom Left Tree Value (C ++ encuentra el valor de la esquina inferior izquierda del árbol)

Ideas de resolución de problemas:

(1) Utilice el mapa para registrar el valor de cada capa

(2) Regrese al primer número guardado en la última capa

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
private:
    map<int,vector<int>> mp;
public:
    void preorder(TreeNode *root,int h) {
        if(!root) return;
        mp[h].push_back(root->val);
        preorder(root->left,h+1);
        preorder(root->right,h+1);
    }
    
    int findBottomLeftValue(TreeNode* root) {
        preorder(root,1);
        int temp;
        for(auto it=mp.begin();it!=mp.end();it++) {
            temp=it->second[0];
        }
        return temp;   
    }
};

 

Supongo que te gusta

Origin blog.csdn.net/coolsunxu/article/details/114916210
Recomendado
Clasificación