二叉树的构造,递归遍历,非递归遍历
来源:互联网 发布:怎么申请不了淘宝直播 编辑:程序博客网 时间:2024/05/19 16:38
二叉树的非递归遍历在面试的时候也会问到,好像后续的非递归遍历比较麻烦,我没有进一步了解,只实现了前序和中序的非递归遍历。
前序:根节点,左孩子,右孩子;
中序:左孩子,根节点,右孩子;
后序:左孩子,右孩子,根节点;
#include <iostream>#include <stack>#include <iostream>using namespace std;struct BinaryTree{ int data; BinaryTree* left; BinaryTree *right;};//中序方式递归遍历二叉树void InOrder(BinaryTree *root){ if (root!=NULL) { InOrder(root->left); cout<<root->data<<" "; InOrder(root->right); } //cout<<endl;}//中序方式非递归遍历二叉树void IterInOrderBinaryTree(BinaryTree *root){ BinaryTree *p=root; stack<BinaryTree *> S; while(p||!S.empty()) { while(p) { S.push(p); p=p->left; } if (!S.empty()) { p=S.top(); S.pop(); cout<<p->data<<" "; p=p->right; } } cout<<endl;}//前序遍历二叉树,递归void Pre(BinaryTree *root){ if (root!=NULL) { cout<<root->data<<" "; Pre(root->left); Pre(root->right); } //cout<<endl;}//前序1遍历二叉树,非递归void PreIter(BinaryTree *root){ stack<BinaryTree *>S; BinaryTree *p=root; while(p||!S.empty()) { while(p!=NULL) { cout<<p->data<<" "; S.push(p); p=p->left; } if (!S.empty()) { p=S.top(); S.pop(); p=p->right; } } cout<<endl;}//以先序方式构造二叉树void ConstructBinaryTree(BinaryTree **root){ int n; cin>>n; if (n<0) { *root=NULL; } else { *root=(BinaryTree*)malloc(sizeof(BinaryTree)); (*root)->data=n; ConstructBinaryTree(&(*root)->left); ConstructBinaryTree(&(*root)->right); }}int main(){ BinaryTree *root=NULL; ConstructBinaryTree(&root); cout<<"递归前序遍历:"; Pre(root); cout<<endl; cout<<"非递归前序遍历:"; PreIter(root); cout<<"递归中序遍历:"; InOrder(root); cout<<endl; cout<<"非递归中序遍历:"; IterInOrderBinaryTree(root); return 0;}
1 0
- 二叉树的构造,递归遍历,非递归遍历
- 二叉树的先中后序遍历,递归遍历,非递归遍历
- 二叉树的递归,非递归遍历
- 二叉树的递归+非递归遍历
- 二叉树的递归非递归遍历
- 二叉树的遍历--递归+非递归
- 二叉树的递归、非递归遍历
- 二叉树的递归非递归遍历
- 二叉树的递归遍历与非递归遍历
- 二叉树的创建,递归遍历,非递归遍历
- 二叉树的递归遍历与非递归遍历
- 二叉树的非递归遍历以及递归遍历
- 二叉树的非递归遍历&递归遍历
- 二叉树的递归遍历和非递归遍历
- 二叉树的递归遍历与非递归遍历
- 二叉树的递归遍历和非递归遍历
- 二叉树的遍历(递归+非递归+层次遍历)
- 二叉树的递归遍历与非递归遍历
- 钻石权威证书有哪些
- Android开发中有关使用ViewFlipper实习手动拖拉替换图片效果
- iOS之数据解析之XML解析
- 94_NavigationView的使用
- hdoj-1028-Ignatius and the Princess III
- 二叉树的构造,递归遍历,非递归遍历
- HDU 3008 dp打怪血量 三重循环调二维背包或一维
- LeetCode Linked List Cycle
- Problem C: 输出不同进制的数
- .net根据经纬度获取地址(百度api)
- centos 的单ip流量控制-CentOS下利用iptables限速及限制每IP连接数
- container_of()宏
- HTML本地数据库localeStorage的应用
- c++ STL 工程实践的15条建议