[leetcode] Binary Tree Postorder Traversal

来源:互联网 发布:it监控软件 编辑:程序博客网 时间:2024/06/02 02:31

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为NULLmystack.push(top->left); top->left = NULL;continue;}if (top->right != NULL){//注意不要忘记设置top->right为NULLmystack.push(top->right); top->right = NULL;continue;}//没有左右子树就输出结果result.push_back(top->val);mystack.pop();//这个时候才pop}return result;}};


0 0