高频算法面试题学习总结----树形结构3:先根遍历

本文介绍二叉树的先根遍历算法,通过递归和栈两种方式实现,展示了具体的C++代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:先根遍历二叉树

输入:root = {1, 2, 3, ­-1, 4, 5, 6}
输出:{1, 2, 4, 3, 5, 6}
解释:
  1
 / \
 2 3
 /\ /\ 
null 4 5 6
root对应的是一个树形结构,­1代表null,正整数代表这个节点的值,每个节点的值全局唯一。

思路1:递归

实现代码:

#include<iostream>
#include<vector>

using namespace std;

void PreOrder(vector<int>& root, int rt)
{
	if (rt < root.size() && root[rt] != -1) {
		cout << root[rt] << " ";
		PreOrder(root, 2 * rt + 1);
		PreOrder(root, 2 * rt + 2);
	}
}
int main()
{
	vector<int> root({ 1,2,3,-1,4,5,6 });
	PreOrder(root, 0);
	cout << endl;
	return 0;
}

思路2:栈

#include<iostream>
#include<vector>
#include<stack>

using namespace std;

void PreOrder(vector<int>& root)
{
	stack<int> s;
	if (!root.empty()) {
		s.push(0);
		while (!s.empty()) {
			int rt = s.top();	s.pop();
			if (2 * rt + 2 < root.size() && root[2 * rt + 2] != -1)
				s.push(2 * rt + 2);	//先添加右孩子
			if (2 * rt + 1 < root.size() && root[2 * rt + 1] != -1)
				s.push(2 * rt + 1);	//后添加左孩子
			cout << root[rt] << " ";
		}
	}
	cout << endl;
}
int main()
{
	vector<int> root({ 1,2,3,-1,4,5,6 });
	PreOrder(root);
	return 0;
}

 

箴言录:

君子成人之美,不成人之恶。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Moyu18_06_12

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值