二叉樹的各種非遞歸遍歷

struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
using node = TreeNode;
/*
先序遍歷1
根-左-右,修改入棧順序可以變成 根-右-左,然後將結果逆序,就是後序遍歷了。
*/
//先序遍歷的第一種寫法。

void preOrderIter(node *root)
{
	if (root == NULL) return;
	stack<node *> s;
	s.push(root);
	while (!s.empty()) 
	{
		node *nd = s.top();
		cout << nd->val << " ";
		s.pop();
		if (nd->right != NULL) s.push(nd->right);
		if (nd->left != NULL) s.push(nd->left);
	}
}

//先序遍歷方法二

//先序2和中序一模一樣,所以記住這一個就行了,如果你基礎薄弱,那麼死記這個,因爲它再稍加修改,就可以變成後序遍歷。

void preOrderIter2(node *root)
{
	stack<node *> s;
	while (root != NULL || !s.empty()) {
		if (root != NULL)
		{
			cout << root->val << " "; //訪問結點併入棧  
			s.push(root);
			root = root->left;         //訪問左子樹  
		}
		else
		{//表示左樹訪問完畢
			root= s.top();            //回溯至父親結點  
			s.pop();//父節點出棧
			root = root->right;        //訪問右子樹  
		}
	}
}

/*
中序遍歷。和先序2只有訪問順序不一樣。

*/

void inOrderIter(node *root)
{
	stack<node *> s;
	while (root != NULL || !s.empty()) {
		if (root != NULL) {
			s.push(root);
			root = root->left;
		}
		else {
			root = s.top();
			cout << root->val << " ";  //訪問完左子樹後才訪問根結點  
			s.pop();
			root = root->right;        //訪問右子樹  
		}
	}
}
/*
後序遍歷1,兩個棧。後序遍歷還可以通過修改先序2來實現

*/

void postOrderIter(node *root)//我們需要把先序遍歷反過來,left和right互換,這和我們第一個先序遍歷很像
{
	if (!root) return;
	stack<node*> s; 
	stack<node*>output;
	s.push(root);//先壓到第一個棧
	while (!s.empty())
	{
		node *curr = s.top();
		output.push(curr);//當前節點壓到輸出棧
		s.pop();
		if (curr->left) s.push(curr->left);
		if (curr->right) s.push(curr->right);
	}
	while (!output.empty()) {//這是依次出棧訪問
		cout << output.top()->val << " ";
		output.pop();
	}
}

/*

後序遍歷2。這是從先序遍歷修改而來,最後需要reverse 容器,實際上就是用它代替棧,

這樣,我們就只需要記憶先序方法2,靈活運用之即可。

*/

vector<int> postorderTraversal(TreeNode* root) {
	stack<TreeNode*> s;
	vector<int> result;
	while (root || !s.empty())
	{
		if (root)
		{
			result.push_back(root->val);//訪問結點併入棧  
			s.push(root);
			root = root->right;         //訪問左子樹  
		}
		else
		{//表示右樹訪問完畢
			root = s.top();            //回溯至父親結點  
			s.pop();//父節點出棧
			root = root->left;        //訪問右子樹  
		}
	}
	reverse(result.begin(), result.end());
	return result;
}

/*

層次遍歷。
這個寫法雖然用了兩個隊列,但是符合真正的層的概念。如果希望剩下一個隊列,你需要記錄隊列長度。
*/

void levelOrderIter(node* root)
{
	if (!root) return;
	queue<node *> currentLevel, nextLevel;
	currentLevel.push(root);
	while (!currentLevel.empty()) {
		node *currNode = currentLevel.front();
		currentLevel.pop();
		if (currNode) {
			cout << currNode->val << " ";
			nextLevel.push(currNode->left);
			nextLevel.push(currNode->right);
		}
		if (currentLevel.empty()) {
			cout << endl;
			swap(currentLevel, nextLevel);
		}
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章