左叶子之和

题目描述:计算给定二叉树的所有左叶子之和。

示例说明请见LeetCode官网。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sum-of-left-leaves/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法一:递归

首先, 如果根节点root为null或者只有一个节点,则说明没有叶子节点,直接返回0;

否则,添加一个递归方法recursive,有2个参数,分别是当前节点的左右子节点,flag为左右子节点的标识,递归过程如下:

  • 调用递归方法recursive,参数分别为root的左右子节点,flag为相应的标识;
  • 判断递归方法中的root如果为null,则返回;
  • 如果root没有左右子节点且且flag标识为左子节点,则将root的值加到结果result中;
  • 否则,递归调用recursive,参数分别为root的左右子节点,flag为相应的标识。

最后,返回result即为所有的左叶子节点之和。

  1. import com.kaesar.leetcode.TreeNode;
  2. /**
  3. * @Author: ck
  4. * @Date: 2021/9/29 7:33 下午
  5. */
  6. public class LeetCode_404 {
  7. /**
  8. * 叶子之和
  9. */
  10. public static int result = 0;
  11. public static int sumOfLeftLeaves(TreeNode root) {
  12. if (root == null || (root.left == null && root.right == null)) {
  13. return 0;
  14. }
  15. recursive(root.left, true);
  16. recursive(root.right, false);
  17. return result;
  18. }
  19. /**
  20. * 递归方法
  21. *
  22. * @param root
  23. * @param flag true表示是左子节点;false表示是右子节点
  24. */
  25. public static void recursive(TreeNode root, boolean flag) {
  26. if (root == null) {
  27. return;
  28. }
  29. if (root.left == null && root.right == null && flag) {
  30. result += root.val;
  31. }
  32. recursive(root.left, true);
  33. recursive(root.right, false);
  34. }
  35. public static void main(String[] args) {
  36. TreeNode root = new TreeNode(3);
  37. root.left = new TreeNode(9);
  38. root.right = new TreeNode(20);
  39. root.right.left = new TreeNode(15);
  40. root.right.right = new TreeNode(7);
  41. // 期望返回值: 24
  42. System.out.println(sumOfLeftLeaves(root));
  43. }
  44. }

【每日寄语】 懒惰者等待机遇,勤奋者创造机遇。