145. Binary Tree Postorder Traversal

来源:互联网 发布:大数据的教育弊端 编辑:程序博客网 时间:2024/05/18 02:47

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?

递归

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    void postOrderTraversal(vector<int>& vi,TreeNode* root)    {        if(root->left) postOrderTraversal(vi,root->left);        if(root->right) postOrderTraversal(vi,root->right);        vi.push_back(root->val);        return;    }    vector<int> postorderTraversal(TreeNode* root) {        vector<int> vi;        if(!root) return vi;        postOrderTraversal(vi,root);        return vi;    }};

pre-order traversal is root-left-right, and post order is left-right-root. modify the code for pre-order to make it root-right-left, and then reverse the output so that we can get left-right-root .

  1. Create an empty stack, Push root node to the stack.
  2. Do following while stack is not empty.

    2.1. pop an item from the stack and print it.

    2.2. push the left child of popped item to stack.

    2.3. push the right child of popped item to stack.

  3. reverse the ouput.

/** * Definition for a binary tree node. * 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> vi;        if(!root) return vi;        stack<TreeNode*> st;        st.push(root);        while(!st.empty())        {          TreeNode* cur_node=st.top();          st.pop();          vi.push_back(cur_node->val);          if(cur_node->left) st.push(cur_node->left);          if(cur_node->right) st.push(cur_node->right);        }        reverse(vi.begin(),vi.end());        return vi;    }};


1 0
原创粉丝点击