p40 路径和是否等于给定值 (leetcode 112)

一:解题思路

第一种方法:递归法

第二种方法:迭代法 ,2种方法的 Time:O(n),Space:O(n)

二:完整代码示例 (C++版和Java版)

递归C++:

class Solution 
{
public:
    bool hasPathSum(TreeNode* root, int sum) 
    {
        if (root == NULL) return false;
        if ((root->left == NULL) && (root->right == NULL)) return root->val == sum;

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

递归Java:

class Solution {
    public boolean hasPathSum(TreeNode root, int sum)
    {
           if(root==null) return false;
           if(root.left==null&&root.right==null) return sum==root.val;

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

迭代C++:

class Solution {
public:
    bool hasPathSum(TreeNode* root, int sum) 
    {
        if (root == NULL) return false;

        stack<TreeNode*> s;
        stack<int> sumStack;

        s.push(root);
        sumStack.push(sum);

        while (!s.empty())
        {
            TreeNode* node = s.top();
            s.pop();
            int n = sumStack.top();
            sumStack.pop();

            if ((node->left == NULL) && (node->right == NULL) && (node->val == n)) return true;

            if (node->left != NULL)
            {
                s.push(node->left);
                sumStack.push(n-node->val);
            }

            if (node->right != NULL)
            {
                s.push(node->right);
                sumStack.push(n-node->val);
            }
        }

        return false;
    }
};

迭代Java:

class Solution {
    public boolean hasPathSum(TreeNode root, int sum)
    {
           if(root==null) return false;
           
           Stack<TreeNode> stack=new Stack<>();
           Stack<Integer> sumStack=new Stack<>();
           
           stack.push(root);
           sumStack.push(sum);
           
           while(!stack.empty())
           {
               TreeNode s=stack.pop();
               int n=sumStack.pop();
               
               if((s.left==null)&&(s.right==null)&&(s.val==n)) return true;
               
               if(s.left!=null)
               {
                   stack.push(s.left);
                   sumStack.push(n-s.val);
               }
               
               if(s.right!=null)
               {
                   stack.push(s.right);
                   sumStack.push(n-s.val);
               }
           }
          
           return false;
    }
}

 

posted @ 2020-03-15 20:26  repinkply  阅读(173)  评论(0)    收藏  举报