左叶子之和

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

示例阐明请见LeetCode官网。

起源:力扣(LeetCode)
链接:https://leetcode-cn.com/probl...
著作权归领扣网络所有。商业转载请分割官网受权,非商业转载请注明出处。

解法一:递归

首先, 如果根节点rootnull或者只有一个节点,则阐明没有叶子节点,间接返回0;

否则,增加一个递归办法recursive,有2个参数,别离是以后节点的左右子节点,flag为左右子节点的标识,递归过程如下:

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

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

import com.kaesar.leetcode.TreeNode;/** * @Author: ck * @Date: 2021/9/29 7:33 下午 */public class LeetCode_404 {    /**     * 叶子之和     */    public static int result = 0;    public static int sumOfLeftLeaves(TreeNode root) {        if (root == null || (root.left == null && root.right == null)) {            return 0;        }        recursive(root.left, true);        recursive(root.right, false);        return result;    }    /**     * 递归办法     *     * @param root     * @param flag true示意是左子节点;false示意是右子节点     */    public static void recursive(TreeNode root, boolean flag) {        if (root == null) {            return;        }        if (root.left == null && root.right == null && flag) {            result += root.val;        }        recursive(root.left, true);        recursive(root.right, false);    }    public static void main(String[] args) {        TreeNode root = new TreeNode(3);        root.left = new TreeNode(9);        root.right = new TreeNode(20);        root.right.left = new TreeNode(15);        root.right.right = new TreeNode(7);        // 冀望返回值: 24        System.out.println(sumOfLeftLeaves(root));    }}
【每日寄语】 懈怠者期待时机,怠惰者发明时机。