【数据结构】创建二叉树的方法

前端之家收集整理的这篇文章主要介绍了【数据结构】创建二叉树的方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

创建普通二叉树的方法

具体可以看代码

  1. //交谈中请勿轻信汇款、中奖信息、陌生电话,勿使用外挂软件。
  2. //
  3.  
  4. #include <iostream>
  5. using namespace std;
  6. typedef struct BiTNode
  7. {
  8. char data;
  9. struct BiTNode *lchild,*rchild;
  10.  
  11. }BiTNode;
  12.  
  13. BiTNode *CreateBinTree ()
  14. {
  15. char ch;
  16. //scanf("%c",&ch);
  17. cin>>ch;
  18. BiTNode *root = (BiTNode*)malloc(sizeof(BiTNode));//根节点
  19.  
  20. if(ch=='#')
  21. root = NULL; //将相应指针置空
  22. else
  23. {
  24. root->data=ch;
  25. root->lchild=CreateBinTree(); //构造左子树
  26. root->rchild=CreateBinTree(); //构造右子树
  27. }
  28.  
  29. return root;
  30. }
  31.  
  32. void preOrder(BiTNode *root)
  33. {
  34. if (root==NULL)
  35. return;
  36. cout<<root->data<<" ";
  37. preOrder(root->lchild);
  38. preOrder(root->rchild);
  39. }
  40.  
  41.  
  42. int main()
  43. {
  44. BiTNode *root = NULL;
  45. cout<<"Please Input The Node:"<<endl;
  46. root = CreateBinTree();
  47.  
  48. cout<<endl;
  49. cout<<"The PreOrder is:";
  50. preOrder(root);
  51. cout<<endl;
  52. return 0;
  53. }
  54.  

猜你在找的数据结构相关文章