https://leetcode.com/problems/deepest-leaves-sum/

1. Use recursion:

  1. //48 ms 28.7 MB
  2. /**
  3. * Definition for a binary tree node.
  4. * struct TreeNode {
  5. * int val;
  6. * TreeNode *left;
  7. * TreeNode *right;
  8. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  9. * };
  10. */
  11. class Solution {
  12. public:
  13. int deepestLeavesSum(TreeNode* root) {
  14. if(!root) return 0;
  15. int result = 0;
  16. int max_depth = maxLeave(root, 0);
  17. deepestLeavesSum(root, 0, result, max_depth);
  18. return result;
  19. }
  20. private:
  21. int maxLeave(TreeNode* root, int depth){
  22. if(!root) return depth - 1;
  23. int d_l = maxLeave(root->left, depth + 1);
  24. int d_r = maxLeave(root->right, depth + 1);
  25. return max(depth, max(d_l, d_r) );
  26. }
  27. void deepestLeavesSum(TreeNode* root, int depth, int& result, int max_depth) {
  28. if(!root) return;
  29. deepestLeavesSum(root->left, depth + 1, result, max_depth);
  30. deepestLeavesSum(root->right, depth + 1, result, max_depth);
  31. //cout << depth << " " << root->val << endl;
  32. //cout << max_depth << " " << (depth == max_depth) << endl;
  33. if(depth == max_depth){
  34. result += root->val;
  35. return;
  36. }
  37. }
  38. };