404. Sum of Left Leaves(统计左叶子节点的和)

妖狐艹你老母 2022-01-05 19:13 265阅读 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. 时间复杂度:on 空间复杂度:o1
  9. /**
  10. * Definition for a binary tree node.
  11. * public class TreeNode {
  12. * int val;
  13. * TreeNode left;
  14. * TreeNode right;
  15. * TreeNode(int x) { val = x; }
  16. * }
  17. */
  18. class Solution {
  19. public int sumOfLeftLeaves(TreeNode root) {
  20. if(root==null) return 0;
  21. if(isLeft(root.left)) return root.left.val+sumOfLeftLeaves(root.right); //找到左子叶之后继续找
  22. return sumOfLeftLeaves(root.left)+sumOfLeftLeaves(root.right);
  23. }
  24. private boolean isLeft(TreeNode root){
  25. if(root==null) return false;
  26. return root.left==null&&root.right==null; //子叶是没有左右孩子的结点
  27. }
  28. }

转载于:https://www.cnblogs.com/shaer/p/10587236.html

发表评论

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

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

相关阅读