LeetCode - Binary Tree Postorder Traversal

来源:互联网 发布:百度霸屏js跳转代码 编辑:程序博客网 时间:2024/05/29 18:12

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?

Recursive solution:

/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    vector<int> postorderTraversal(TreeNode *root) {        vector<int> result;        if(root==NULL){            return result;        }                if(root->left!=NULL){            vector<int>leftResult = postorderTraversal(root->left);            result.insert(result.end(),leftResult.begin(),leftResult.end());        }                if(root->right!=NULL){            vector<int> rightResult = postorderTraversal(root->right);            result.insert(result.end(),rightResult.begin(),rightResult.end());        }                result.push_back(root->val);                return result;    }};
Iterative solution:

/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    vector<int> postorderTraversal(TreeNode *root) {        vector<int> result;        if(root==NULL){            return result;        }                stack<pair<TreeNode*,bool> > nodeStack;        nodeStack.push(make_pair(root,false));                while(!nodeStack.empty()){            pair<TreeNode*,bool>& tmp=nodeStack.top();            if(tmp.second){                result.push_back(tmp.first->val);                nodeStack.pop();            }else{                tmp.second = true;                            bool hasChild = false;                if(tmp.first->right!=NULL){                    nodeStack.push(make_pair(tmp.first->right,false));                    hasChild = true;                }                if(tmp.first->left!=NULL){                    nodeStack.push(make_pair(tmp.first->left,false));                    hasChild = true;                }                                if(!hasChild){                     result.push_back(tmp.first->val);                     nodeStack.pop();                }            }        }        return result;    }};

0 0
原创粉丝点击