笔试题:求二叉树和值为sum的所有路径
2015-09-06 17:00
399 查看
#include <iostream> #include <stack> using namespace std; struct TreeNode { int data; TreeNode *left; TreeNode *right; TreeNode(int d = int()):data(d), left(NULL), right(NULL){} }; class Tree { public: Tree() :root(NULL){} void Insert(int VLR[], int LVR[],int n) { Insert(root, VLR, LVR, n); } void Printf() { Printf(root); } void PrintfSum(int sum) { stack<TreeNode*> st; PrintfSum(root, st,sum); } private: void PrintfSum(TreeNode* t, stack<TreeNode*>& st,int sum) { if (t == NULL) { if (sum == 0) { stack<TreeNode *> sp = st; while (sp.empty() == false) { cout << sp.top()->data << " "; sp.pop(); } cout << endl; } //st.pop(); return; } else { st.push(t); sum -= t->data; PrintfSum(t->left, st,sum); if (t->right!=NULL) PrintfSum(t->right, st,sum); st.pop(); } } void Insert(TreeNode *&t, int VLR[], int LVR[], int n) { if (n == 0)return; int i = 0; while (VLR[0] != LVR[i])i++; t = new TreeNode(VLR[0]); Insert(t->left, VLR + 1, LVR, i); Insert(t->right, VLR + i + 1, LVR + i+1, n - i - 1); } void Printf(TreeNode *t) { if (t != NULL) { cout << t->data << " "; Printf(t->left); Printf(t->right); } } private: TreeNode *root; }; int main() { Tree t; int VLR[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}; int LVR[] = {4,3,6,5,7,2,9,8,10,1,12,11,13,14,15,16}; t.Insert(VLR,LVR,sizeof(LVR)/sizeof(int)); t.Printf(); cout << endl; t.PrintfSum(24); return 0; }
相关文章推荐
- 论文提要“Filtered Channel Features for Pedestrian Detection”
- Spring AOP使用整理:使用@AspectJ风格的切面声明
- python中的lambda表达式
- 分享一个在网页嵌入二维码的方法
- 往textarea中光标所在位置插入文本
- IOS第18天(2,CALayer自定义图层)
- 扣取头发
- 易元平台使用
- 机房收费系统 之 总体理解
- CentOS进入单用户模式
- 如何将一个HTML页面嵌套在另一个页面中
- 如何开启和关闭定时器
- UVA 211 The Domino Effect
- LRU CACHE
- 机房收费系统之常用语句
- Android Region代码分析
- Android第一步
- treap(树堆)
- 线性回归 Linear Regression
- Java多线程实现同时进行小球的自由落体与平抛