标签: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; }
标签:style blog color ar for 数据 div 代码 sp
原文地址:http://www.cnblogs.com/ruccsbingo/p/3957899.html