C++二插树和值与子树求解
2015-06-14 17:46
399 查看
#include <iostream> #include <stack> using namespace std; template<typename Type> struct Node { Type data; Node *left; Node *right; Node(Type d = Type()):data(d), left(NULL), right(NULL){} }; template<typename Type> class MyTree { public: MyTree(const char *str) { root = NULL; flags = '#'; Init(root, str); } void Printf() { Printf(root); } bool IsSonTree(Type a,Type b) { return IsSonTree(GetPtr(a),GetPtr(b)); } Type GetValue(Type a) { return GetPtr(a)->data; } Node<Type> * GetPtr(Type a) { return GetPtr(root, a); } void Sum(int x)//打印和值为x的二叉树。 { int sum = 0; stack<Node<Type> *> st;//借助一个栈来实现。 Sum(root, x,sum,st); } private: int Sum(Node<Type> *t,int x,int sum,stack<Node<Type>*> st)//此处不能用引用传递st。 { if (t == NULL) { return 0; } if (t) { sum += t->data - '0'; st.push(t); if (sum == x) { while (st.empty() == false) { Node<Type> *p = st.top(); st.pop(); cout << p->data << " "; } cout << endl; sum = 0;//将sum设置为0,继续递归寻找其他和值等于x的路径。 } if (sum > x)//如果此路大于x,则直接跳出这条路继续递归。 { return 0; } Sum(t->left, x, sum, st); Sum(t->right, x, sum, st); } } bool IsSonTree(Node<Type> *t, Node<Type> *p)//判断p树是不是t树的子树。 { if (t == NULL)return false; else { if (t == p) return Find(t, p);//每次找到一个节点相等,就进入Find函数进行递归判断看是否所有的节点都相等。 bool BOOL = IsSonTree(t->left, p); if (BOOL)return BOOL; return IsSonTree(t->right, p); } return false; } bool Find(Node<Type> *t, Node<Type> *p) { if (t == p)return true; if (t != NULL) { bool BOOL = Find(t->left,p); if (BOOL)return true; return Find(t->right, p); } return false; } Node<Type>* GetPtr(Node<Type> *t,Type a) { if (t!=NULL && t->data == a)return t; if (t) { Node<Type> *tmp = GetPtr(t->left, a); if (tmp)return tmp; return GetPtr(t->right, a); } return NULL; } void Printf(Node<Type> *t) { if (t != NULL) { cout << t->data << " "; Printf(t->left); Printf(t->right); } } void Init(Node<Type> *&t, const char *&s) { if (*s == flags) { t = NULL; return; } else { t = new Node<Type>(*s); Init(t->left,++s); Init(t->right, ++s); } } private: Node<Type> *root; Type flags; }; int main() { MyTree<char> mt("123##4##51##7##"); mt.Sum(7);//求和值为定值的所有路径。 //mt.Printf(); //cout << endl; //cout << mt.IsSonTree('1','7') << endl; return 0; }
相关文章推荐
- C/C++的学习 持续更新
- C语言文件处理-对图片取模数据的转换
- C++ 静态成员函数调用非静态成员函数方法
- C++打印位数为n的所有数
- VC++ 自定义控件的建立及使用方法
- block 实现原理和相关内存管理详解
- (C++)C++类继承中的构造函数和析构函数
- c++11 Chrono时间库
- [C/C++]_[中级]_[使用智能指针的方式释放malloc出来的堆空间]
- [C/C++]_[中级]_[使用智能指针的方式释放malloc出来的堆空间]
- 【深度探索C++对象模型读书笔记】【第6章】执行期语意学
- 【深度探索C++对象模型读书笔记】【第6章】执行期语意学
- C 语言(一)
- 数组和指针作为函数参数——高质量C、C++编程指南
- 一起talk C栗子吧(第十七回:C语言实例--栈二)
- C++ 智能指针详解
- (C++)浅谈using namespace std
- 《C++Primer》读书笔记--命名空间
- C++函数编译的几种方式解析
- 自己按照书上实现的c语言的单链表