leetcode:path sum(I) 递归与非递归解法

来源:互联网 发布:网络课程有哪些 编辑:程序博客网 时间:2024/04/30 13:45

Path Sum

 Total Accepted: 12663 Total Submissions: 42061My Submissions

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

For example:
Given the below binary tree and sum = 22,
              5             / \            4   8           /   / \          11  13  4         /  \      \        7    2      1

return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

递归解法:

class Solution{

public:

     bool hasPathSum(TreeNode *root, int sum) {

  if(!root)

  return false;

  else if(root->val == sum && !root->left && !root->right)

return true;

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

};

};

非递归解法:定义两个栈,一个存放前序遍历的结点,一个存放前序遍历时的结点累加值;

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool hasPathSum(TreeNode *root, int sum) {
        if(!root)
          return false;
       stack<TreeNode *> stk;
       stack<int> tempSum;
       
       stk.push(root);
       tempSum.push(root->val);
       while(!stk.empty())
       {
           TreeNode *nd = stk.top();
           stk.pop();
           int tpm = tempSum.top();
           tempSum.pop();
           if(nd->left == NULL && nd->right == NULL && tpm == sum)
           {
               return true;
           }
           if(nd->left)
           {
               stk.push(nd->left);
               tempSum.push(tpm + nd->left->val);
           }
           if(nd->right)
           {
               stk.push(nd->right);
               tempSum.push(tpm + nd->right->val);
           }
       }
       return false;
    }
};

0 0
原创粉丝点击