当前位置:   article > 正文

类实现之二叉树_有一个树的类,结构如下,class tree{ node head;class node{int v

有一个树的类,结构如下,class tree{ node head;class node{int val; node parent;
  1. #include <stdio.h>
  2. #include <queue>
  3. using namespace std;
  4. class Node
  5. {
  6. public:
  7. Node* father;
  8. int num;
  9. Node* left;
  10. Node* right;
  11. Node()
  12. {
  13. father=NULL;
  14. left=NULL;
  15. right=NULL;
  16. }
  17. Node(int num):num(num)
  18. {
  19. father=NULL;
  20. left=NULL;
  21. right=NULL;
  22. }
  23. ~Node()
  24. {
  25. }
  26. };
  27. class DTree
  28. {
  29. public:
  30. Node* proot;
  31. DTree()
  32. {
  33. proot=NULL;
  34. }
  35. ~DTree()
  36. {
  37. }
  38. void GetFather(Node* pNode)
  39. {
  40. do
  41. {
  42. printf("%d\n",pNode->num);
  43. pNode=pNode->father;
  44. }while(pNode!=NULL);
  45. }
  46. void DFS(Node* pNode)
  47. {
  48. printf("%d\n",pNode->num);
  49. if(pNode->left!=NULL) DFS(pNode->left);
  50. if(pNode->right!=NULL) DFS(pNode->right);
  51. }
  52. void BFS(Node* pNode)
  53. {
  54. queue<Node*> q;
  55. q.push(pNode);
  56. while(q.size()>0)
  57. {
  58. Node* pcur=q.front();
  59. q.pop();
  60. printf("%d\n",pcur->num);
  61. if(pcur->left!=NULL) q.push(pcur->left);
  62. if(pcur->right!=NULL) q.push(pcur->right);
  63. }
  64. }
  65. };
  66. int main()
  67. {
  68. Node root(0);
  69. Node l(1); l.father=&root; root.left=&l;
  70. Node ll(3); ll.father=&l; l.left=&ll;
  71. Node lr(4); lr.father=&l; l.right=&lr;
  72. Node r(2); r.father=&root; root.right=&r;
  73. Node rl(5); rl.father=&r; r.left=&rl;
  74. Node rr(6); rr.father=&r; r.right=&rr;
  75. DTree tree;
  76. tree.proot=&root;
  77. tree.GetFather(&lr);
  78. printf("\n");
  79. tree.DFS(&root);
  80. printf("\n");
  81. tree.BFS(&root);
  82. return 0;
  83. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/457139
推荐阅读
相关标签
  

闽ICP备14008679号