高頻算法面試題學習總結----樹形結構3:先根遍歷

題目:先根遍歷二叉樹

輸入: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;
}

 

箴言錄:

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章