Find Bottom Left Tree Value(C++找树左下角的值)

超、凢脫俗 2022-10-22 10:53 226阅读 0赞

解题思路:

(1)使用map记录每层的数值

(2)返回最后一层第一个保存的数

  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode() : val(0), left(nullptr), right(nullptr) {}
  8. * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  9. * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  10. * };
  11. */
  12. class Solution {
  13. private:
  14. map<int,vector<int>> mp;
  15. public:
  16. void preorder(TreeNode *root,int h) {
  17. if(!root) return;
  18. mp[h].push_back(root->val);
  19. preorder(root->left,h+1);
  20. preorder(root->right,h+1);
  21. }
  22. int findBottomLeftValue(TreeNode* root) {
  23. preorder(root,1);
  24. int temp;
  25. for(auto it=mp.begin();it!=mp.end();it++) {
  26. temp=it->second[0];
  27. }
  28. return temp;
  29. }
  30. };

发表评论

表情:
评论列表 (有 0 条评论,226人围观)

还没有评论,来说两句吧...

相关阅读