1. 程式人生 > >建立排序二叉樹並中序遍歷

建立排序二叉樹並中序遍歷

分析:中序遍歷也叫中根遍歷,顧名思義是把根節點放在中間來遍歷,其遍歷順序為左子節點–>根節點–>右子節點。

方法一:

#include<iostream>
using 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 13
Press any key to continue