建立排序二叉树并中序遍历

网友投稿 578 2022-10-09 07:40:14

建立排序二叉树并中序遍历

分析:中序遍历也叫中根遍历,顾名思义是把根节点放在中间来遍历,其遍历顺序为左子节点–>根节点–>右子节点。

方法一:

#includeusing namespace std;struct node //二叉树结点结构{ int data; node *left; //右子树结点指针 node *right; //左子树结点指针};class Btree{ node *root; //根结点的指针public: Btree() { root = NULL; } void CreateBtree(int); void Inorder() //中序遍历主过程 { Inorder(root); cout << endl; } void Inorder(node *); //中序遍历子过程};void Btree::CreateBtree(int x){ node *newnode = new node; newnode->data = x; newnode->left = NULL; newnode->right = NULL; if(NULL == root) { root = newnode; } else { node *back; node *current = root; while(current != NULL) //找到要插入newnode的节点指针 { back = current; if(current->data > x) { current=current->left; } else { current = current->right; } } if(back->data > x) { back->left = newnode; } else { back->right = newnode; } }}void Btree::Inorder(node *root) //中序遍历排序二叉树{ if(root) { Inorder(root->left); cout << root->data << " "; Inorder(root->right); }}int main(){ Btree A; int arr[]={7, 4, 1, 5, 12, 8, 13, 11}; //排序二叉树:左子结点<根节点<右子节点 cout << "建立排序二叉树:" << endl; for(int i = 0; i < 8; i++) { cout << arr[i] << " "; A.CreateBtree(arr[i]); } cout << endl << "中序遍历序列:" << endl; A.Inorder(); return 0;}

运行结果:

建立排序二叉树:7 4 1 5 12 8 13 11中序遍历序列:1 4 5 7 8 11 12 13Press any key to continue

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:云沃客微信小程序(微信小程序)
下一篇:小程序复刻版EOS Knights
相关文章