1. 程式人生 > >94. Binary Tree Inorder Traversal(+樹的遍歷非遞迴)

94. Binary Tree Inorder Traversal(+樹的遍歷非遞迴)

題意:

非遞迴中序遍歷。

樹的先序遍歷

vector<int> preorderTraversal(TreeNode* root) {
	stack<TreeNode*> s;
	vector<int> res;
	TreeNode *p = root;
	while (p || !s.empty()) {
		while (p) {
			s.push(p);
			//res.push_back(p->val);
			p = p->left;
		}
		if (!s.empty()) {
			p = s.top();
s.pop(); p = p->right; } } return res; }

中序遍歷

vector<int> inorderTraversal(TreeNode* root) {
	stack<TreeNode*> s;
	vector<int> res;
	TreeNode *p = root;
	while (p || !s.empty()) {
		while (p) {
			s.push(p);
			p = p->left;
		}
		if (!s.empty()) {
			p = s.top
(); res.push_back(p->val); s.pop(); p = p->right; } } return res; }

後序遍歷

void PostOrder(TreeNode *root) {
    TreeNode *p = root, *r = NULL;
    stack<TreeNode*> s;
    while (p || !s.empty()) {
        if (p) {//走到最左邊
            s.push(p);
            p = p->left;
        }
else { p = s.top(); if (p->right && p->right != r)//右子樹存在,未被訪問 p = p->right; else { s.pop(); visit(p->val); r = p;//記錄最近訪問過的節點 p = NULL;//節點訪問完後,重置p指標 } }//else }//while }