7

LeetCode-404-左叶子之和

 2 years ago
source link: https://segmentfault.com/a/1190000040767758
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

LeetCode-404-左叶子之和

发布于 53 分钟前

左叶子之和

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

示例说明请见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));
    }
}

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK