Binary Tree Postorder Traversal

来源:互联网 发布:网络会员制营销的概念 编辑:程序博客网 时间:2024/06/05 22:50

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?

Subscribe to see which companies asked this question

class Solution {public:    vector<int> postorderTraversal(TreeNode *root) {        // IMPORTANT: Please reset any member data you declared, as        // the same Solution instance will be reused for each test case.        vector<int> ans;        list<TreeNode*> node_list;        if(root == NULL) return ans;        node_list.push_front(root);        TreeNode *head = root;        while(!node_list.empty())        {            TreeNode *cur = node_list.front();                        if(cur -> right == head || cur -> left == head || ((cur -> right == NULL) && (cur -> left == NULL)))            {                node_list.pop_front();                ans.push_back(cur -> val);                head = cur;            }            else            {                if(cur -> right != NULL) node_list.push_front(cur -> right);                if(cur -> left != NULL) node_list.push_front(cur -> left);            }        }    }};


0 0
原创粉丝点击