leetcode:path sum(I) 递归与非递归解法
来源:互联网 发布:网络课程有哪些 编辑:程序博客网 时间:2024/04/30 13:45
Path Sum
Total Accepted: 12663 Total Submissions: 42061My SubmissionsGiven 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;
}
};
- leetcode:path sum(I) 递归与非递归解法
- LeetCode path Sum i ,ii递归和迭代解法
- LeetCode 112. Path Sum--递归
- LeetCode之maxDepth非递归解法
- Leetcode Symmetric Tree 递归和非递归解法
- 【LeetCode】Path Sum II 二叉树递归
- [leetcode]Path Sum--巧用递归
- Binary Tree Maximum Path Sum Java 递归解法
- 背包非递归解法
- Fibonacci非递归解法
- 字符串反序函数的递归与非递归解法
- 关于回溯算法的递归与非递归解法
- N皇后问题递归与非递归解法
- N皇后问题的递归与非递归解法
- 单链表反转的递归与非递归解法
- leetcode 39. Combination Sum-回溯算法|递归|非递归
- 汉诺塔问题的递归解法与非递归解法(堆栈解法)
- 递归与非递归
- native2ascii插件配置
- NIO作用简介及其相关知识
- lua 知识点记录
- 动态规划问题总结
- 国宾礼炮有讲究:总理级别19响 元首级别21响
- leetcode:path sum(I) 递归与非递归解法
- PADS中创建不规则焊盘
- STL之全排列
- Android代码混淆
- undefined reference问题总结
- Bellman-Ford算法
- System V信号量(1)
- ajax开发
- 媲美韩寒 上海传智学员佳作《钥匙》