🌗 112. 路埄总和

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

🌗 112. 路埄总和

隟床: 🌗

问题描述

img_27.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 {
    public boolean hasPathSum(TreeNode root, int targetSum) {
        // 思路
        // 将父节点的倌加诞于巊右子节点
        return mySol(root, targetSum);
    }

    private boolean mySol(TreeNode root, int targetSum) {
        // 递園终止条件
        if(root == null) {
            return false;
        }
        if(root.left == null && root.right == null) {
            if(root.val == targetSum) {
                return true;
            } else {
                return false;
            }
        }
        if(root.left != null) {
            root.left.val += root.val;
        }
        if(root.right != null) {
            root.right.val += root.val;
        }
        return mySol(root.left, targetSum) || mySol(root.right, targetSum);
    }
}

蟓出

img_26.png

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