Deepest Leaves Sum(C++层数最深叶子节点的和)

亦凉 2022-12-29 14:18 281阅读 0赞

解题思路:

(1)先遍历求出最深的深度值

(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. int max = 0,sum = 0;
  15. public:
  16. void preorder(TreeNode *root,int h) {
  17. if(root!=NULL) {
  18. if(h>max) max = h;
  19. preorder(root->left,h+1);
  20. preorder(root->right,h+1);
  21. }
  22. }
  23. void getsum(TreeNode *root,int h) {
  24. if(root!=NULL) {
  25. if(h==max) sum+=root->val;
  26. getsum(root->left,h+1);
  27. getsum(root->right,h+1);
  28. }
  29. }
  30. int deepestLeavesSum(TreeNode* root) {
  31. int h = 0;
  32. preorder(root,h);
  33. getsum(root,h);
  34. return sum;
  35. }
  36. };

发表评论

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

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

相关阅读