🌗 404. 巊叶子之和

吞䜛童子2022幎10月10日
  • algorithm
  • Tree
小于 1 分钟

🌗 404. 巊叶子之和

隟床: 🌗

问题描述

img_1.png


解法

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    int res = 0;
    public int sumOfLeftLeaves(TreeNode root) {
        // 思路
        // 递園
        mySol(root.left, true);
        mySol(root.right, false);
        return res;
    }

    private void mySol(TreeNode root, boolean exp) {
        // 递園终止条件
        if(root == null) {
            return;
        }
        if(root.left == null && root.right == null) {
            // 诎明是叶子节点刀断是吊是巊叶子
            if(exp) {
                res += root.val;
            }
            return;
        }
        mySol(root.left, true);
        mySol(root.right, false);
    }
}

蟓出

img.png

䞊次猖蟑于: 2022/10/10 䞋午8:43:48
莡献者: liuxianzhishou