二叉树前序遍历

前序遍历,就是 根-左-右 的顺序。

有递归和非递归的解法,递归还分遍历和分治两种解法,下面直接给出代码


递归遍历的解法,最直观的代码,这里需要辅助函数

vector<int> preorder(Tree* root) {
	vector<int> res;
	preoder_rec(root, res);  // 不需要判NULL,函数内部会处理
	return res;
}
	
void preorder_rec(Tree* root, vector<int>& res) {
	if (root == NULL) return;
	res.push_back(root->val);
	preorder_rec(root->left, res);  // 不需要判NULL,函数内部会处理
	preorder_rec(root->right, res); // 不需要判NULL,函数内部会处理
}


递归分治的解法,就是分别算出左右子树的结果然后合并成总结果

vector<int> preorder(Tree* root) {
	vector<int> res;
	if (root == NULL) return res;
	
	vector<int> left = preorder(root->left);
	vector<int> right = preorder(root->right);
	
	res.push_back(root->val);
	res.insert(res.end(), left.begin(), left.end());
	res.insert(res.end(), right.begin(), right.end());
	
	return res;
}


迭代的解法,需要使用一个栈进行辅助,先将root压栈

然后不断从栈顶取出元素,并将其值放入结果向量中,然后再将左右非空子节点逆序压入堆栈

不断循环,直到栈空

最后向量中就是所求结果

vector<int> preorder(Tree* root) {
	vector<int> res;
	if (root == NULL) return res;
	
	stack<Tree*> s;
	s.push(root);  //栈用的push,不是push_back
	while (!s.empty()) {
		Tree* node = s.top();
		s.pop();
		res.push_back(node->val);
		if (node->right) s.push(node->right); //注意压栈顺序是反的!非常容易出错!
		if (node->left) s.push(node->left);
	}
	
	return res;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值