[leetcode] Binary Tree Postorder Traversal

Given a binary tree, return the postorder traversal of its nodes' values.

For example:
Given binary tree {1,#,2,3},

   1
    \
     2
    /
   3

return [3,2,1].

Note: Recursive solution is trivial, could you do it iteratively?


遞歸版本:

class Solution
{
private:
    std::vector<int> result;
public:
    vector<int> postorderTraversal(TreeNode *root)
    {
        post_traver(root);
        return result;
    }
    void post_traver(TreeNode * p)
    {
        if(p==NULL) return;//代碼太簡單,無需註釋吧!
        post_traver(p->left);
        post_traver(p->right);
        result.push_back(p->val);
    }
};

非遞歸版本:

class Solution
{
private:
	std::vector<int> result;
public:
	vector<int> postorderTraversal(TreeNode *root)
	{
		stack<TreeNode *> mystack;//使用堆棧,替換函數遞歸
		if (root != NULL) mystack.push(root);
		while (!mystack.empty())
		{
			TreeNode * top = mystack.top();//堆棧頭部
			if (top == NULL) continue;
			if (top->left != NULL)
			{//注意不要忘記設置top->left爲NULL
				mystack.push(top->left); top->left = NULL;
				continue;
			}
			if (top->right != NULL)
			{//注意不要忘記設置top->right爲NULL
				mystack.push(top->right); top->right = NULL;
				continue;
			}
			//沒有左右子樹就輸出結果
			result.push_back(top->val);
			mystack.pop();//這個時候才pop
		}

		return result;
	}
};


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