My comprehension of O(n) solution from @hongzhi

  • 32

    Below is the O(n) solution from @hongzhi but that discuss is closed now 'cause @hongzhi says little about his code.

    I've modified some of and tried this code and got AC.
    Just share about some comprehension about his code.

    I've modified vtn(vector) to stn(stack) in that stack is probably what this algs means and needs.

    What matters most is the meaning of stn.

    Only nodes whoes left side hasn't been handled will be pushed into stn.

    And inorder is organized as (inorder of left) root (inorder of right),

    And postorder is as (postorder of left) (postorder of right) root.

    So at the very begin, we only have root in stn and we check if inorder.back() == root->val and in most cases it's false(see Note 1). Then we make this node root's right sub-node and push it into stn.

    Note 1: this is actually (inorder of right).back() == (postorder of right).back(), so if only there's no right subtree or the answer will always be false.

    Note 2: we delete one node from postorder as we push one into stn.

    Now we have [root, root's right] as stn and we check inorder.back() ==>val again.

    • true means inorder.back() is the root node and needs handled left case.
    • false means inorder.back() is the next right sub-node

    So when we encounter a true, we will cache as p and delete both nodes from inorder and stn.

    Then we check inorder.size(), if there's no nodes left, it means p has no left node.

    Else the next node in inorder could be p's left node or p's father which equals to the now (remember we popped p from stn above).

    If the latter happens, it means p has no left node and we need to move on to p's father(

    If the former happens, it means p has one left node and it's postorder.back(), so we put it to p's left and delete it from the postorder and push the left node into stn 'cause it should be the next check node as the postorder is organized as above.

    That's all of it. The algs just build a binary tree. :)

    Inform me if there's anything vague or wrong, I'm open to any suggestions.

    class Solution {
        TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
            if(inorder.size() == 0)return NULL;
            TreeNode *p;
            TreeNode *root;
            stack<TreeNode *> stn;
            root = new TreeNode(postorder.back()); 
                if(inorder.back() ==>val) 
                    p =;
                    if(inorder.size() == 0) break;
                    if(stn.size() && inorder.back() ==>val)
                    p->left = new TreeNode(postorder.back()); 
                    p = new TreeNode(postorder.back());
          >right = p; 
            return root;

  • 1

    Thanks and +1 for your detailed explanation.

  • 7

    Thank you for sharing your explanation.

    Here's a Java version of this solution:

    import java.util.Stack;
    public class Solution {
        public TreeNode buildTree(int[] inorder, int[] postorder) {
            if (inorder == null || inorder.length < 1) return null;
            int i = inorder.length - 1;
            int p = i;
            TreeNode node;
            TreeNode root = new TreeNode(postorder[postorder.length - 1]);
            Stack<TreeNode> stack = new Stack<>();
            while (true) {
                if (inorder[i] == stack.peek().val) { // inorder[i] is on top of stack, pop stack to get its parent to get to left side
                    if (--i < 0) break;
                    node = stack.pop();
                    if (!stack.isEmpty() && inorder[i] == stack.peek().val) {// continue pop stack to get to left side
                    node.left = new TreeNode(postorder[p]);
                } else { // inorder[i] is not on top of stack, postorder[p] must be right child
                    node = new TreeNode(postorder[p]);
                    stack.peek().right = node;
            return root;

  • 0

    Thank you for your detailed explanation!

    And here is the python version:

    class Solution:
        # @param inorder, a list of integers
        # @param postorder, a list of integers
        # @return a tree node
        def buildTree(self, inorder, postorder):
            if len(inorder) == 0:
                return None
            root = TreeNode(postorder.pop())
            stn = list()
            while True:
                if inorder[-1] == stn[-1].val:
                    p = stn.pop()
                    if len(inorder) == 0: break
                    if len(stn) != 0 and inorder[-1] == stn[-1].val: continue
                    p.left = TreeNode(postorder.pop())
                    p = TreeNode(postorder.pop())
                    stn[-1].right = p
            return root

  • 0

    Still too hard to understand. The logic is very unusual.

    Serialization of the recursive version could actually suffice what you said, i guess. So no mystery. Work out the recursive version first. then use stack to do it iteratively

  • 1

    Thanks for your idea! I think your code will change the input parameters postorder and inorder, so I just changed it a little bit by using two integers to record the indexes of current elements in postorder and inorder. Now this code will not change the input parameters at all.

    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
    	if (inorder.size() == 0 || postorder.size() == 0)
    		return 0;
    	TreeNode* root = new TreeNode(postorder.back());
    	if (postorder.size() == 1)
    		return root;
    	stack<TreeNode*> st;
    	int i = postorder.size() - 2;
    	int j = inorder.size() - 1;
    	TreeNode* node;
    	while (true)
    		if (>val == inorder[j])
    			node =;
    			if (j < 0)
    			if (!st.empty() &&>val == inorder[j])
    			node->left = new TreeNode(postorder[i]);
    			node = new TreeNode(postorder[i]);
    			i--;>right = node;
    	return root;

  • 0
    This post is deleted!

  • 0

    Take a look at this explanation for pre and in case, similar thought but clearer explanation.

  • 0

    clear rewrite, i do learn something. just FYI, Stack is deprecated somehow, you can use Deque instead.

  • 0

    go through the code several times, really cool :p upvoted

  • 0

    Great solutions! Thanks for sharing.

    I thought the explanation is still a bit difficult to understand so I wrote a simpler one with comments and high-level understanding of this approach. It uses index so does not modify original parameters.

    Hope it helps.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.