二叉树的三种非递归遍历

来源:互联网 发布:电脑制作漫画软件 编辑:程序博客网 时间:2024/05/19 23:10
struct TreeNode{int val;TreeNode *left;TreeNode *right;};
一、前序输出二叉树void PreOrder(TreeNode *root){if(root==NULL)return;stack<TreeNode*> stk;TreeNode *p = root;while(p!=NULL||!stk.empty()){while(p!=NULL){cout<<p->val<<endl;stk.push(p);p = p->left;}p = stk.top();stk.pop();p = p->right;}}
二、中序输出二叉树void MidOrder(TreeNode *root){if(root==NULL)return;stack<TreeNode*> stk;TreeNode *p = root;while(p!=NULL||!stk.empty()){while(p!=NULL){stk.push(p);p = p->left;}p = stk.top();cout<<p->val<<endl;stk.pop();p = p->right;}}
void PostOrder(TreeNode* root){if(root==NULL)return;stack<TreeNode*> stk;TreeNode *p=root;TreeNode* visited = NULL;//将p移动到左子树最下边while(p!=NULL){stk.push(p);p=p->left;}while(!stk.empty()){p = stk.top();stk.pop();//一个根节点被访问的前提是:无右子树或右子树已经被访问if(p->right==NULL || p->right==visited){cout<<p->val<<endl;visited = p;}else{//根节点再次入栈stk.push(p);//进入右子树,且可肯定右子树一定不为空p = p->right;while(p!=NULL){stk.push(p);p = p->left;}}}}


四、从上到下,从左至右输出二叉树

void PrintHorizonal(TreeNode *root){if(root==NULL)return;vector<TreeNode*> q;q.push_back(root);int i = 0;while(i<q.size()){cout<<q[i]->val<<endl;if(q[i]->left!=NULL)q.push_back(q[i]->left);if(q[i]->right!=NULL)q.push_back(q[i]->right);i++;}}

五、之字形打印二叉树

vector<vector<int>> Print(TreeNode* root){queue<TreeNode*> que;vector<vector<int>> fin;if(root==NULL)return fin;que.push(root);bool eve = false;while(!que.empty()){const int size = que.size();vector<int> tmp;for(int i=0;i<size;i++){TreeNode *f = que.front();tmp.push_back(f->val);que.pop();if(f->left)que.push(f->left);if(f->right)que.push(f->right);}if(eve)reverse(tmp.begin(),tmp.end());fin.push_back(tmp);eve = !eve;}return fin;}

六、输出二叉树第K个小的点的值

int KthSmallestNode(TreeNode *root,int k){if(root==NULL)return;stack<TreeNode*> stk;TreeNode *p = root;while(p!=NULL||!stk.empty()){while(p!=NULL){stk.push(p->left);p = p->left;}p = stk.top();if(--k==0)return p->val;stk.pop();p = p->right;}return -1;}



                                             
0 0