Problem 112

Sum Path

Posted by Ruizhi Ma on June 29, 2019

问题描述

见链接:https://leetcode.com/problems/path-sum/

解决思路

其实就是深度优先(DFS),不断递归左右子树。

代码

package leetcode;

public class PathSum {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) { val = x; }
    }

    public boolean hasPathSum(TreeNode root, int sum) {

        if(root == null) return false;

        if(root.val == sum && root.left == null && root.right == null) return true;

        return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
    }
}