二叉树遍历是非常基础的基本技能,主要有深度优先, 广度优先(层序遍历),还有前中后序遍历。
这里就用C++实现一下。
附赠二叉树结构和一个二叉树实例用于测试。
struct TreeNode {
TreeNode(int a) {
val = a;
left = NULL;
right = NULL;
}
TreeNode* left;
TreeNode* right;
int val;
};
int main() {
TreeNode* root = new TreeNode(1);
root->left= new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
root->right->left = new TreeNode(6);
root->right->right = new TreeNode(7);
//遍历方法
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
1.深度优先遍历(递归)
void deep(TreeNode* root) {
if (!root) return;
cout << root->val << " ";
if (root->left)
deep(root->left);
if (root->right)
deep(root->right);
}
非递归
void dfs(TreeNode* root) {
stack<TreeNode*> s;
s.push(root);
while (!s.empty()) {
TreeNode* tmp = s.top();
cout << tmp->val<<" ";
s.pop();
if (tmp->right) s.push(tmp->right);
if (tmp->left) s.push(tmp->left);
}
}
2.广度优先遍历(层序遍历)
借助辅助队列
void layer(TreeNode* root) {
if (!root) return;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
TreeNode* tmp = q.front();
q.pop();
cout << tmp->val<<" ";
if (tmp->left)
q.push(tmp->left);
if (tmp->right)
q.push(tmp->right);
}
}
3.前序遍历(非递归)
借助辅助栈
void pre(TreeNode* root) {
if (!root)return;
stack<TreeNode*> s;
while (root || !s.empty()) {
while (root) {
cout << root->val<<" ";
s.push(root);
root = root->left;
}
if (!s.empty()) {
root = s.top();
s.pop();
root = root->right;
}
}
}
4.中序遍历(非递归)
就是在前序遍历的基础上将输出语句改到if(!s.empty())里就行了。
void mid(TreeNode* root) {
if (!root)return;
stack<TreeNode*> s;
while (root || !s.empty()) {
while (root) {
s.push(root);
root = root->left;
}
if (!s.empty()) {
root = s.top();
s.pop();
cout << root->val << " ";
root = root->right;
}
}
}
5.后序遍历(非递归)
不仅需要辅助栈,还需要一个记录节点。
void rear(TreeNode* root) {
if (!root)return;
stack<TreeNode*> s;
TreeNode* visit=NULL;
while (root || !s.empty()) {
while (root) {
s.push(root);
root = root->left;
}
root = s.top();
if (root->right==visit||root->right==NULL) {
cout << root->val << " ";
s.pop();
visit = root;
root = NULL;
}
else {
root = root->right;
}
}
}