Java solution (using Preorder Traversal )

  • 0
    public class Solution {
    boolean ans = false;
    public boolean hasPathSum(TreeNode root, int sum) {
            return false;
        searchTree(root , 0 ,sum) ;
        return ans;
    public void searchTree( TreeNode root, int preSum , int sum){
        int nowSum = root.val + preSum;
        if(root.left==null && root.right==null && nowSum==sum )//if to the leaf, check is the path equals the given sum 
            ans = true ;
            searchTree( root.left, nowSum , sum);
            searchTree( root.right, nowSum , sum);


Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.