二叉树的非递归遍历c++实现(与递归进行了对比)
作者:互联网
条件:【1】需要将原来树的节点重新封装,封装后的结构中具有对原来树节点的一个flag描述;
【2】利用STL中的栈容器实现对节点的入栈以及出栈操作;
拿下图为例:
注意:该段代码实现的是前序遍历,如果想要实现中序/后序遍历 只需将第48-49行代码与前俩行代码调换位置即可。该段代码没有对new过的节点进行delete。(暂时不知道怎么delete !-!)。
1 #include<iostream> 2 #include<stack> 3 using namespace std; 4 5 const int My_False = 0; //或者采用宏:#define My_False 0;这里参考Effective c++ 做法 6 const int My_True = 1; 7 8 //二叉树原始节点 9 struct BinaryNode 10 { 11 char ch; 12 BinaryNode* lchild; 13 BinaryNode* rchild; 14 }; 15 //封装了flag的节点 16 struct BiTreeStackNode 17 { 18 BinaryNode* root; 19 int flag; 20 }; 21 //创建封装后栈中的节点 22 BiTreeStackNode* CreateBiTreeStackNode(BinaryNode* node, int flag) { 23 BiTreeStackNode* newnode = new BiTreeStackNode; 24 newnode->root = node; 25 newnode->flag = flag; 26 return newnode; 27 } 28 //非递归遍历 29 void NonRecursion(BinaryNode* root) { 30 //创建栈 31 stack<BiTreeStackNode*> stack; 32 //把当前封装后节点入栈 33 stack.push(CreateBiTreeStackNode(root, My_False)); 34 while (!stack.empty()) { 35 //先弹出栈顶元素 36 BiTreeStackNode* node = stack.top(); 37 stack.pop(); 38 //判断弹出的节点是否为空 39 if (node->root == NULL) continue; 40 if (node->flag == My_True) cout << node->root->ch<<" "; 41 else 42 { 43 //当前封装后节点中原始节点的右节点入栈 44 stack.push(CreateBiTreeStackNode(node->root->rchild, My_False)); 45 //当前封装后节点中原始节点的左节点入栈 46 stack.push(CreateBiTreeStackNode(node->root->lchild, My_False)); 47 //将当前节点的flag改为My_True并重新压栈 48 node->flag = My_True; 49 stack.push(node); 50 } 51 } 52 } 53 //递归遍历 54 void Recursion(BinaryNode* root) { 55 if (!root) return; 56 57 cout << root->ch << " "; 58 Recursion(root->lchild); 59 Recursion(root->rchild); 60 } 61 //初始化二叉树 62 void CreateBinaryTree() { 63 BinaryNode node1 = { 'A',NULL,NULL }; 64 BinaryNode node2 = { 'B',NULL,NULL }; 65 BinaryNode node3 = { 'C',NULL,NULL }; 66 BinaryNode node4 = { 'D',NULL,NULL }; 67 BinaryNode node5 = { 'E',NULL,NULL }; 68 BinaryNode node6 = { 'F',NULL,NULL }; 69 BinaryNode node7 = { 'G',NULL,NULL }; 70 BinaryNode node8 = { 'H',NULL,NULL }; 71 //建立节点关系 72 node1.lchild = &node2; 73 node1.rchild = &node6; 74 node2.rchild = &node3; 75 node3.lchild = &node4; 76 node3.rchild = &node5; 77 node6.rchild = &node7; 78 node7.lchild = &node8; 79 //二叉树的非递归打印 80 cout << "二叉非树递归遍历:\n"; 81 NonRecursion(&node1); 82 cout << endl<<"二叉树递归遍历:\n"; 83 Recursion(&node1); 84 } 85 86 int main() { 87 CreateBinaryTree(); 88 }
先序:
中序:
后序:
标签:递归,My,c++,flag,二叉树,NULL,root,节点,BinaryNode 来源: https://www.cnblogs.com/jibisheng/p/12951254.html