二叉树的遍历(中序,非递归)

    已知一棵二叉树,要求遍历该树。

    对于普通的二叉树,有两种办法,递归和非递归。非递归一般使用一个栈数据结构,来模拟递归时栈的变化。

    对于节点中包含父节点指针的树,非递归遍历可以不使用栈结构,使用一个标志变量和父节点指针进行遍历。

 

    示例:

    二叉树的中序遍历,代码仅做参考

#include <stdio.h> #include <stdlib.h> #include <memory.h> #include <Windows.h> /* 树节点 */ typedef struct tagNode { tagNode * pParent; tagNode * pLeft; tagNode * pRight; int m_i; } Node; /* 构造树 遍历树,求所有节点的和,中序 销毁树 */ void test() { Node * pTree = NULL; Node * pNode = NULL; Node * pParent = NULL; int sum = 0; int dir = 0; pTree = new Node; memset( pTree, 0, sizeof(Node) ); srand( GetTickCount() ); /* 构造树 */ for ( int i = 0; i < 1000; i++ ) { int r = rand()%1000; sum += r; pNode = pTree; if ( pNode->pParent == NULL ) { pNode->m_i = r; pNode->pParent = pNode; continue; } pParent = NULL; while ( pNode != NULL ) { pParent = pNode; if ( r < pNode->m_i ) { pNode = pNode->pLeft; dir = 0; } else { pNode = pNode->pRight; dir = 1; } } pNode = new Node; memset( pNode, 0 , sizeof(Node) ); pNode->m_i = r; pNode->pParent = pParent; if ( dir == 0 ) { pParent->pLeft = pNode; } else { pParent->pRight = pNode; } } printf( "%d/n", sum ); /* 中序遍历 */ pTree->pParent = NULL; pParent = pTree; pNode = pParent->pLeft; sum = 0; dir = 0; while ( pParent != NULL ) { /* 左向下 */ if ( dir == 0 && pNode->pLeft != NULL ) { pParent = pNode; pNode = pParent->pLeft; continue; } /* 右向下 */ if ( dir == 0 && pNode->pRight != NULL ) { sum += pNode->m_i; pParent = pNode; pNode = pParent->pRight; continue; } /* 叶节点 */ if ( dir == 0 ) { sum += pNode->m_i; } /* 左向上 */ if ( pNode == pParent->pLeft ) { sum += pParent->m_i; if ( pParent->pRight != NULL ) { pNode = pParent->pRight; dir = 0; continue; } } /* 右向上 */ pNode = pParent; pParent = pParent->pParent; dir = 1; } printf( "%d/n", sum ); /* 销毁树 */ pParent = pTree; pNode = pParent->pLeft; sum = 0; while ( pParent != NULL ) { if ( pNode->pLeft != NULL ) { pParent = pNode; pNode = pNode->pLeft; continue; } if ( pNode->pRight != NULL ) { pParent = pNode; pNode = pNode->pRight; continue; } sum += pNode->m_i; delete pNode; if ( pNode == pParent->pLeft ) { pParent->pLeft = NULL; if ( pParent->pRight != NULL ) { pNode = pParent->pRight; } else { pNode = pParent; pParent = pParent->pParent; } } else { pParent->pRight = NULL; pNode = pParent; pParent = pParent->pParent; } } sum += pTree->m_i; delete pTree; printf("%d/n",sum); return; } int main( int argc, char ** argv ) { test(); return 0; }

你可能感兴趣的:(数据结构,struct,null,delete)