2021.11.11 - SX07-18.路径总和

1. 题目

在这里插入图片描述
在这里插入图片描述

2. 思路

(1) 递归

  • 利用递归处理四种结点的判断逻辑即可。

(2) 递归优化

  • 递归的简化写法。

3. 代码

public class Test {
    
    
    public static void main(String[] args) {
    
    
    }
}

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 {
    
    
    private int targetSum;

    public boolean hasPathSum(TreeNode root, int targetSum) {
    
    
        if (root == null) {
    
    
            return false;
        }
        this.targetSum = targetSum;
        return recur(root, 0);
    }

    private boolean recur(TreeNode root, int sum) {
    
    
        int cur = sum + root.val;
        if (root.left == null && root.right == null) {
    
    
            return cur == targetSum;
        } else if (root.left != null && root.right != null) {
    
    
            return recur(root.left, cur) || recur(root.right, cur);
        } else if (root.left != null) {
    
    
            return recur(root.left, cur);
        } else {
    
    
            return recur(root.right, cur);
        }
    }
}

class Solution1 {
    
    
    public boolean hasPathSum(TreeNode root, int targetSum) {
    
    
        if (root == null) {
    
    
            return false;
        }
        if (root.left == null && root.right == null) {
    
    
            return targetSum == root.val;
        }
        return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_44021223/article/details/121271672
sx