题目:先根遍历二叉树
输入: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;
}
箴言录:
君子成人之美,不成人之恶。