类实现之二叉树
来源:互联网 发布:人脸识别是人工智能吗 编辑:程序博客网 时间:2024/06/05 20:06
#include <stdio.h>#include <queue>using namespace std;class Node{public: Node* father; int num; Node* left; Node* right; Node() { father=NULL; left=NULL; right=NULL; } Node(int num):num(num) { father=NULL; left=NULL; right=NULL; } ~Node() { }};class DTree{public: Node* proot; DTree() { proot=NULL; } ~DTree() { } void GetFather(Node* pNode) { do { printf("%d\n",pNode->num); pNode=pNode->father; }while(pNode!=NULL); } void DFS(Node* pNode) { printf("%d\n",pNode->num); if(pNode->left!=NULL) DFS(pNode->left); if(pNode->right!=NULL) DFS(pNode->right); } void BFS(Node* pNode) { queue<Node*> q; q.push(pNode); while(q.size()>0) { Node* pcur=q.front(); q.pop(); printf("%d\n",pcur->num); if(pcur->left!=NULL) q.push(pcur->left); if(pcur->right!=NULL) q.push(pcur->right); } }};int main(){ Node root(0); Node l(1); l.father=&root; root.left=&l; Node ll(3); ll.father=&l; l.left=≪ Node lr(4); lr.father=&l; l.right=&lr; Node r(2); r.father=&root; root.right=&r; Node rl(5); rl.father=&r; r.left=&rl; Node rr(6); rr.father=&r; r.right=&rr; DTree tree; tree.proot=&root; tree.GetFather(&lr); printf("\n"); tree.DFS(&root); printf("\n"); tree.BFS(&root); return 0;}