LeetCode 145 Binary Tree Postorder Traversal (C++, Python)

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?

Solution C++

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
 * 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> ret;
        if (root == NULL) return ret;
        stack<TreeNode*> mystack;
        deque<int> temp;
        mystack.push(root);
        while (!mystack.empty()) {
            TreeNode* node = mystack.top();
            mystack.pop();
            temp.insert(temp.begin(), node->val);
            if (node->left)
                mystack.push(node->left);
            if (node->right)
                mystack.push(node->right);
        }
        ret.assign(temp.begin(), temp.end());
        return ret;
    }
};

Solution Python


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# Definition for a  binary tree node
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
from collections import deque
class Solution:
    # @param root, a tree node
    # @return a list of integers
    def postorderTraversal(self, root):
        ret = []
        if not root: return []
        mystack = [root]
        buf = deque([])
        while mystack:
            node = mystack.pop()
            buf.appendleft(node.val)
            if node.left:
                mystack.append(node.left)
            if node.right:
                mystack.append(node.right)
        ret.extend(buf)
        return ret

Popular posts from this blog

How Django Works (4) URL Resolution

Python Class Method and Class Only Method

How Django works (3): Testing Server and Static Files Serving