(C/C++学习)31.二叉树的遍历

说明:二叉树是一种非常重要的数据结构。对于二叉树,有两种遍历方式:深度遍历和广度遍历。其中深度遍历有前序、中序以及后序三种遍历方式。而广度遍历及常说的层次遍历。

1. 四种基本遍历的思想:

     前序遍历:根节点->左子树->右子树

     中序遍历:左子树->根节点->右节点

     后续遍历:左子树->右子树->根节点

     广度遍历:从上至下从左至右依次遍历

需要注意的是:对于每一子树也应该按照相应的遍历思想进行递归遍历。

举例,如下二叉树:

     前序遍历:ABDECF (根左右)

     中序遍历:DBEAFC (左根右)

     后续遍历:DEBFCA (左右根)

     广度遍历:ABCDEF (从上至下从左至右)

2. 面试常考点:根据遍历结果确定一棵二叉树

    a. 已知前序遍历和中序遍历的结果,可以确定一棵唯一的二叉树结构,

    b. 已知后续遍历和中序遍历的结果,可以确定一棵唯一的二叉树结构,

    c. 已知前序遍历和后续遍历的结果,不能确定一棵唯一的二叉树结构。

 3. 程序示例:

 1 #include<iostream>
 2 #include<queue>
 3 #include<stack>
 4 using namespace std;
 5 /*二叉树树节点*/
 6 class BT {
 7 public:
 8     BT(int data=0,BT* left=0,BT* right=0):_data(data),_left(left),_right(right) {}
 9     int _data;
10     BT* _left;
11     BT* _right;    
12 };
13 /*创建二叉树*/
14 void CreatBT(BT *&root) {
15     int data = 0;
16     cin>>data;
17     if(data != -1) {
18         root = new BT(data,0,0);
19         CreatBT(root->_left);
20         CreatBT(root->_right);
21     }    
22 }
23 /*删除二叉树*/
24 void DeleteBT(BT* root){
25     if(!root) 
26         return ;
27     DeleteBT(root->_left);
28     DeleteBT(root->_right);
29     delete root;        
30 }
31 
32 /*二叉树前序遍历*/
33 void ForTrans(BT* root) {
34     if(!root)
35         return ;    
36     cout<<root->_data<<" ";
37     ForTrans(root->_left);
38     ForTrans(root->_right);    
39 }
40 /*二叉树中序遍历*/
41 void CenTrans(BT* root) {
42     if(!root)
43         return ;
44     CenTrans(root->_left);
45     cout<<root->_data<<" ";
46     CenTrans(root->_right);    
47 }
48 /*二叉树后序遍历*/
49 void NexTrans(BT* root) {
50     if(!root)
51         return ;
52     NexTrans(root->_left);
53     NexTrans(root->_right);
54     cout<<root->_data<<" ";    
55 }
56 
57 /*二叉树深度遍历非递归版*/
58 void DepTrans(BT *root) {
59     if(!root)
60         return ;
61     stack<BT*> s;
62     s.push(root);
63     while(!s.empty()) {
64         BT *temp = s.top();
65         s.pop();
66         cout<<temp->_data<<" ";
67         if(temp->_right)
68             s.push(temp->_right);
69         if(temp->_left)
70             s.push(temp->_left);    
71     }     
72 }
73 /*二叉树广度遍历*/
74 void BroTrans(BT *root) {
75     queue<BT*> q;
76     q.push(root);
77     while(!q.empty()) {
78         BT *temp = q.front();
79         q.pop();
80         cout<<temp->_data<<" ";
81         if(temp->_left)
82             q.push(temp->_left);
83         if(temp->_right)
84             q.push(temp->_right);     
85     }
86 }
87 
88 int main() {
89     BT* root = NULL;
90     CreatBT(root);
91     cout<<"PreOrder: ";    ForTrans(root);  cout<<endl;
92     cout<<"CenOrder: ";    CenTrans(root);  cout<<endl;
93     cout<<"NexOrder: ";    NexTrans(root);  cout<<endl;   
94     cout<<"BroOrder: ";    BroTrans(root);  cout<<endl;
95     cout<<"DepOrder: ";    DepTrans(root);  cout<<endl;
96     DeleteBT(root);
97     cout << "Hello,World!\n";
98     return 0;
99 } 
View Code

猜你喜欢

转载自www.cnblogs.com/tuihou/p/12442664.html
今日推荐