二叉树的遍历(更新中)
来源:互联网 发布:网红拍照软件 编辑:程序博客网 时间:2024/05/22 00:31
本文记录二叉树的几种遍历方式,包括:前序,中序,后序三种遍历方式的递归与非递归实现以及层次遍历。
前序:根,左,右;
中序:左,根,右;
后序:左,右,根;
层次:按层从左到右。
/* define of binary treetypedef struct Tree{ int value; Tree *left, *right;}*BinaryTree;*/
1, 前序遍历:
非递归实现:
typedef struct Node{ BinaryTree index; int flag; //记录栈中每个元素的状态:0表示还未遍历该节点的左子树,1表示已经遍历了左子树。 };void inorderTraversal(TreeNode *root) {if(root == NULL) return;stack<Node>st;Node n;n.pointer = root;n.flag = 0;st.push(n);while(!st.empty()){Node top = st.top();if(top.flag == 0){st.top().flag = 1;if(top.pointer->left != NULL){Node tmp;tmp.pointer = top.pointer->left;tmp.flag = 0;st.push(tmp);}}else{st.pop();cout<<top.pointer->value<<endl; //visitif(top.pointer->right != NULL){Node tmp;tmp.pointer = top.pointer->right;tmp.flag = 0;st.push(tmp);}}}}
2, 中序遍历:
3, 后序遍历:
递归实现:
void postOrder(BinaryTree root){if(root == NULL) return;postOrder(root->left);postOrder(root->right);printf("%d ", root->value);}
非递归实现:
typedef struct Node{ BinaryTree index; int flag; //记录栈中每个元素的状态:0表示还未遍历该节点的左右子树,1表示已经遍历了左子树还未遍历右子树,2表示已经遍历完了左右子树。};void postorder_no_re(BinaryTree root){ if(root == NULL) return; stack<Node>st; Node tmp; tmp.index = root; tmp.flag = 0; st.push(tmp); while(!st.empty()) { Node top = st.top(); if(top.flag == 2) //当左右子树都已遍历完成,现在就该遍历当前节点 { printf("%d ", top.index->value); st.pop(); } else if(top.flag == 0) //需要遍历左子树 { st.top().flag = 1; BinaryTree left = top.index->left; if(left != NULL) { Node node; node.index = left; node.flag = 0; st.push(node); } } else // 遍历右子树 { st.top().flag = 2; BinaryTree right = top.index->right; if(right != NULL) { Node node; node.index = right; node.flag = 0; st.push(node); } } }}
4, 层次遍历:
- 二叉树的遍历(更新中)
- 二叉树的遍历(2):中序遍历
- 二叉树的遍历(1)--先序遍历,中序遍历,后序遍历
- 二叉树的遍历(前序遍历、中序遍历、后序遍历)
- 二叉树的遍历代码(先序遍历,中序遍历,后序遍历)
- 二叉树的遍历,二叉树的创建、前序遍历、中序遍历、后序遍历 (转)
- 二叉树的建立及遍历(先序遍历、中序遍历、后续遍历、层次遍历)
- 二叉树的前序遍历,中序遍历和后序遍历(c#)
- 二叉树T 的先序遍历、中序遍历、后序遍历(递归实现)
- 二叉树的遍历(递归遍历)
- 二叉树的中序遍历(树)
- 二叉树的遍历(中序,非递归)
- 二叉树的中序遍历(非递归)
- 二叉树的中序遍历(递归)
- 二叉树的中序遍历(非递归)
- 二叉树的遍历(前、中、后序)
- 数据库中实现二叉树的遍历
- C#中实现二叉树的遍历
- oracle sql日期
- getOutputStream() has already been called for this response异常的原因和解决方法
- 编程之美 2013 全国挑战赛 资格赛 题目三 树上的三角形
- C++ 异常处理(基础篇)
- 电容充放电
- 二叉树的遍历(更新中)
- apache:2.2.17 php 5.3.5
- 应该被记住的8位Java人物
- Holmos自动化测试入门学习(一)-------打开/关闭浏览器&&页面常用方法举例
- Linux (ubuntu)下安装eclipse
- 【Oracle】-【show_space和show_space_asm】-执行存储过程show_space和show_space_asm报错
- android应用程序安装位置android:installLocation翻译
- 为什么计算机和一些电子产品的时间选择在1970.1.1
- Android LayoutInflater的使用