404. Sum of Left Leaves (二叉树中左叶子值之和)

缺乏、安全感 2022-07-15 01:38 227阅读 0赞

Find the sum of all left leaves in a given binary tree.

Example:

  1. 3
  2. / \
  3. 9 20
  4. / \
  5. 15 7
  6. There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
  7. /**
  8. * Definition for a binary tree node.
  9. * public class TreeNode {
  10. * int val;
  11. * TreeNode left;
  12. * TreeNode right;
  13. * TreeNode(int x) { val = x; }
  14. * }
  15. */
  16. public class Solution {
  17. public int sumOfLeftLeaves(TreeNode root) {
  18. if(root==null)
  19. return 0;
  20. if(root.left==null)
  21. return sumOfLeftLeaves(root.right);
  22. if(root.left.left==null&&root.left.right==null)
  23. return root.left.val+sumOfLeftLeaves(root.right);
  24. return sumOfLeftLeaves(root.left)+sumOfLeftLeaves(root.right);
  25. }
  26. }

发表评论

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

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

相关阅读