二叉树各种遍历

二叉树遍历是非常基础的基本技能,主要有深度优先, 广度优先(层序遍历),还有前中后序遍历。
这里就用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;
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值