二叉树深度优先遍历和广度优先遍历

来源:互联网 发布:怎么下载淘宝网 编辑:程序博客网 时间:2024/04/30 04:25

二叉树先序、后序、中序遍历非递归版本请参照:


二叉树非递归先序遍历、中序遍历、后序遍历


深度优先遍历:

int bitreeDeepOrder(bitreeNode * root){stack<bitreeNode *> st;st.push(root);//printf("%d,", root->value);do{root = st.top();st.pop();printf("%d,", root->value);if(root->right)st.push(root->right);if(root->left)st.push(root->left);if(st.empty())break;}while(1);return 0;}

广度优先遍历:


int bitreeWideOrder(bitreeNode * root){queue<bitreeNode *> qu;qu.push(root);//printf("%d,", root->value);do{root = qu.front();qu.pop();printf("%d,", root->value);if(root->left)qu.push(root->left);if(root->right)qu.push(root->right);if(qu.empty())break;}while(1);return 0;}

实验:

#define BITREE_SIZE 10int _tmain(int argc, _TCHAR* argv[]){bitreeNode * root = (bitreeNode *)malloc(sizeof(bitreeNode) * BITREE_SIZE);for(int i=0; i<BITREE_SIZE; i++){root[i].value = i;if((i * 2 +1) < BITREE_SIZE)root[i].left = &(root[i*2+1]);elseroot[i].left = NULL;if((i * 2 + 2) < BITREE_SIZE)root[i].right = &(root[i*2 + 2]);elseroot[i].right = NULL;}bitreeDeepOrder(root);printf("\n");bitreeWideOrder(root);return 0;}




0 0