[Leetcode 113, Medium] Path sum II
2015-08-04 01:41
459 查看
Problem:
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:
Given the below binary tree and
return
Analysis:
Solutions:
C++:
A recursive solution: (16 ms)
A non-recursive solution: (16 ms)
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:
Given the below binary tree and
sum = 22,
5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1
return
[ [5,4,11,2], [5,8,4,5] ]
Analysis:
Solutions:
C++:
A recursive solution: (16 ms)
void getPath(TreeNode *root, int sum, vector<vector<int> > &path, vector<int> &curPath) { if(root==NULL) return; if(root->left==NULL && root->right==NULL && root->val==sum){ curPath.push_back(root->val); path.push_back(curPath); curPath.erase(curPath.end()-1, curPath.end()); }else{ curPath.push_back(root->val); if(root->left!=NULL) getPath(root->left, sum-root->val, path, curPath); if(root->right!=NULL) getPath(root->right, sum-root->val, path, curPath); curPath.erase(curPath.end()-1, curPath.end()); } } vector<vector<int> > pathSum(TreeNode *root, int sum) { vector<vector<int> > path; if(root==NULL) return path; vector<int> curPath(1, root->val); if(root->left==NULL && root->right==NULL && root->val==sum) path.push_back(curPath); if(root->left!=NULL) getPath(root->left, sum-root->val, path, curPath); if(root->right!=NULL) getPath(root->right, sum-root->val, path, curPath); return path; }
A non-recursive solution: (16 ms)
vector<vector<int>> pathSum(TreeNode* root, int sum) { vector<vector<int>> results; if(root == NULL) return results; stack<TreeNode *> node_stack; TreeNode *p_cur = root; TreeNode *visited = NULL; vector<int> result; while(p_cur || !node_stack.empty()) { if(p_cur) { sum -= p_cur->val; result.push_back(p_cur->val); if(p_cur->left == NULL && p_cur->right == NULL && sum == 0) { results.push_back(result); } node_stack.push(p_cur); p_cur = p_cur->left; } else { p_cur = node_stack.top(); if(p_cur->right == NULL || p_cur->right == visited) { sum += p_cur->val; result.erase(result.end() - 1); node_stack.pop(); visited = p_cur; p_cur = NULL; } else p_cur = p_cur->right; } } return results; }
相关文章推荐
- Netroid学习笔记(二):请求的使用
- Netroid学习笔记(一):初识Netroid
- android m classpath
- poj 2352 Stars (树状数组)
- IOS开发基础之UIImage
- Android SQLite学习指南
- BootStrap媒体对象
- 黑马程序员——正则表达式
- BZOJ4049 : [Cerc2014] Mountainous landscape
- OC学习笔记11--protocol使用方法及注意事项
- Weka初体验——中文文本分类
- POJ 1091 跳蚤(分解质因数 + 容斥 + 大数)
- java 定时器
- POJ2001 字典树
- 矩阵构造方法
- CodeRush使用教程一:代码分析
- 欢迎使用CSDN-markdown编辑器
- javaScript 页面自动加载事件详解
- 2015.8.4
- 算法设计与分析:第二章 递归 2.2买商品