二叉树的三种遍历方法
2014-12-25 14:53
405 查看
/******************定义二叉树**************************/ //链式存储 struct BinaryTreeNode { int mValue; BinaryTreeNode* mLeft; BinaryTreeNode* mRight; }; //顺序存储 struct BinaryTreeNode { int data[MAX_SIZE]; int length; } /******************递归实现***************************/ //先序遍历 int PreOrderTreeWalk(BinaryTreeNode* pNode) { if(pNode == NULL) return 0; printf(pNode->mValue); PreOrderTreeWalk(pNode->mLeft); PreOrderTreeWalk(pNode->mRight); return 1; } //中序遍历 int InOrderTreeWalk(BinaryTreeNode* pNode) { if(pNode == NULL) return 0; PreOrderTreeWalk(pNode->mLeft); printf(pNode->mValue); PreOrderTreeWalk(pNode->mRight); return 1; } //后序遍历 int PostOrderTreeWalk(BinaryTreeNode* pNode) { if(pNode == NULL) return 0; PreOrderTreeWalk(pNode->mLeft); PreOrderTreeWalk(pNode->mRight); printf(pNode->mValue); return 1; } /*****************非递归实现***********************/ //先序遍历 int PreOrderTreeWalk(BinaryTreeNode* pNode) { std::Stack<BinaryTreeNode*> stack; if(pNode == NULL) return 0; while(!stack.empty()||pNode) { while(pNode) { //先访问 printf(pNode->mValue); stack.push(pNode); //遍历左节点 pNode = pNode->mLeft; } //弹出根节点 pNode = stack.top(); stack.pop(); //遍历右节点 pNode = pNode->mRight; } } //中序遍历 int int InOrderTreeWalk(BinaryTreeNode* pNode) { std::Stack<BinaryTreeNode*> stack; if(pNode == NULL) return 0; while(!stack.empty()||pNode) { while(pNode!=NULL) { stack.push(pNode); pNode = pNode->mLeft; } pNode = stack.top(); stack.pop(); printf(pNode->mValue); pNode = pNode->mRight; } } //后序遍历,用一个标记标记右子树是否访问过 int PostOrderTreeWalk(BinaryTreeNode* pNode) { std::Stack<BinaryTreeNode*> stack; boolean flag[MAX_SIZE]; if(pNode == NULL) return 0; stack.push(pNode); flag[stack.size()-1] = false; while(!stack.empty()||pNode) { pNode = stack.top(); //左子树入栈,初始化 while(pNode) { stack.push(pNode); flag[stack.size()-1] = false;//标记此时该节点右子树并未被访问 pNode = pNode-> mLeft; } //访问到最左节点 pNode = stack.top(); //访问右子树 if(pNode->mRight&&!flag[stack.size()-1]) { flag[stack.size()-1] = true; pNode = pNode-> mRight; } else { pNode = stack.top(); stack.pop(); printf(pNode->mValue); } } }
相关文章推荐
- 二叉树初始化及三种遍历方法
- 二叉树的三种遍历的方法(递归和非递归完整版)
- 二叉树的三种迭代遍历方法
- 用非递归方式实现二叉树的前、中、后三种遍历方法
- 二叉树的三种遍历方法实现
- 二叉树的三种遍历方法(递归和非递归)(转载)
- 二叉树的三种遍历方法(递归和非递归)
- 二叉树的前序遍历三种方法
- 二叉树的三种遍历方法(递归)
- 重温数据结构:二叉树的常见方法及三种遍历方式 Java 实现
- 二叉树的三种遍历方法(递归和非递归)(转载)
- 数据结构 二叉树的建立及三种遍历方法
- 遍历二叉树的三种方法
- 二叉树前序遍历的三种方法
- 二叉树的三种遍历方法(递归和非递归)(转载)
- 二叉树的三种遍历方法(递归和非递归)
- 二叉树三种遍历方法(根据两种排序求第三种的顺序)
- 二叉树的三种遍历方式(递归和非递归的实现方法)
- 数据结构之二叉树 (构造 拷贝构造 以及前序中序后续三种遍历方法)
- 二叉树的创建和前中后三种遍历方法