非遞迴遍曆二叉樹之中序遍曆

來源:互聯網
上載者:User

標籤:style   blog   color   ar   for   資料   div   代碼   sp   

//中序遍曆
int inorder_tree_walk(BinTreeNode * root){ if(root == NULL){ return -1; } stack<BinTreeNode *> s; BinTreeNode * p = root; while(!s.empty() || p != NULL) { while(p != NULL){ s.push(p); p = p->lchild; } p = s.top(); s.pop(); cout << p->key<< endl; p = p->rchild; } return 0;}

 紅色的部分表示訪問元素的值,和前序走訪二叉樹相比,他們的區別僅僅在於訪問元素的位置不同

建立一個二叉樹

int insert(BinTreeNode * root, BinTreeNode * node){    if(root == NULL || node == NULL)    {        cout << "insert root and node should not be NULL" << endl;        return -1;    }    BinTreeNode * p = root;    while(p != NULL){        if(node->key < p->key){            if(p->lchild == NULL){                p->lchild = node;                return 0;            }            else                p = p->lchild;        }        else{            if(p->rchild == NULL){                p->rchild = node;                return 0;            }            else                p = p->rchild;        }    }    return 0;}

定義的資料結構

typedef struct BinTreeNode{    int key;    char * data;    BinTreeNode * lchild;    BinTreeNode * rchild;}BinTreeNode;typedef struct BinTree{    int size;    BinTreeNode * root;}BinTree;

測試代碼

int main(){    BinTreeNode root;    memset(&root, 0, sizeof(root));    root.key = 9;    BinTreeNode* btn;    for(int i=0; i<10; i++)    {        btn = (BinTreeNode *) malloc(sizeof(BinTreeNode));        memset(btn, 0, sizeof(btn));        int k = i*13155443 % 17;        cout << k << " ";        btn->key = k;        insert(&root, btn);    }    cout << endl;    inorder_tree_walk2(&root);    return 1;}

 

非遞迴遍曆二叉樹之中序遍曆

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.