二叉树系列三:二叉树的遍历(递归方法)

二叉树的遍历分为前序遍历、中序遍历、后序遍历和层次遍历四种,下面分别进行简要的阐述并用C++实现:

(1)前序遍历

前序遍历首先访问结点,然后访问其左右子树,如果使用递归算法,那么具体的实现如下:

 1 template<class T>
 2 void Tree<T>::PreOrder(TreeNode<T>* root)
 3 {
 4     if(root != NULL)
 5     {
 6         cout<<root->data<<endl;
 7         PreOrder(root->leftChild);
 8         PreOrder(root->rightChild);
 9     }
10 }
View Code

(2)中序遍历

中序遍历首先遍历其左子树,然后访问结点,最后遍历右子树,递归实现如下:

 1 template<class T>
 2 void Tree<T>::MidOrder(TreeNode<T>* root)
 3 {
 4     if(root != NULL)
 5     {
 6         MidOrder(root->leftChild);
 7         cout<<root->data<<endl;
 8         MidOrder(root->rightChild);
 9     }
10 }
View Code

(3)后序遍历

后续遍历首先遍历结点的左右子树,然后访问结点,递归实现如下:

 1 template<class T>
 2 void Tree<T>::PostOrder(TreeNode<T>* root)
 3 {
 4     if(root != NULL)
 5     {        
 6         PostOrder(root->leftChild);
 7         PostOrder(root->rightChild);
 8         cout<<root->data<<endl;
 9     }
10 }
View Code

(4)层次遍历(非递归)

 此方法中不适用递归方法,而是借助队列,访问当前结点后,将其左右子女(非左右子树)压入队列中,然后弹出队列中的第一个元素,按照同样的方法处理,代码实现如下:

 1 template<class T>
 2 void Tree<T>::LevelOrder(TreeNode<T>* root)
 3 {
 4     if(root != NULL)
 5     {    
 6         queue<TreeNode<T>*> q;
 7         TreeNode<T>* curr = root;
 8         TreeNode<T>* temp = root;
 9         while(curr)
10         {
11             cout<<curr->data<<endl;
12             if(curr->leftChild)
13                 q.push(curr->leftChild);
14             if(curr->rightChild)
15                 q.push(curr->rightChild);
16             if(!q.empty())
17             {
18                 curr = q.front();
19                 q.pop();
20             }
21             else
22                 curr = NULL;
23         }
24     }
25 }
View Code

 

 

posted on 2013-06-19 15:56  Sophia-呵呵小猪  阅读(242)  评论(0编辑  收藏  举报