Blogs Hub

by Sumit Chourasia | Nov 17, 2020 | Category :coding | Tags : algorithm array data-structure leetcode medium

Construct Binary Tree from Inorder and Postorder Traversal - Array - Medium - LeetCode

Construct Binary Tree from Inorder and Postorder Traversal - Array - Medium - LeetCode

Given inorder and postorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

For example, given

inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]
Return the following binary tree:

    3
   / \
  9  20
    /  \
   15   7

 

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
public class Solution {
    public TreeNode BuildTree(int[] inorder, int[] postorder) {
        return Helper(postorder.Length-1, 0, inorder.Length-1, inorder, postorder);
    }
    
    private TreeNode Helper(int postIndex, int inStart, int inEnd, int[] inorder, int[] postorder){
        if(postIndex<0 || inStart > inEnd){
            return null;
        }
        
        var root = new TreeNode(postorder[postIndex]);
        int i= postorder.Length -1;
        for(;i>=0;i--){
            if(inorder[i]==root.val){
                break;
            }
        }
        
        root.left = Helper(postIndex - 1 - inEnd + i, inStart, i - 1, inorder, postorder);
        root.right = Helper(postIndex - 1 , i + 1, inEnd, inorder, postorder);
        
        return root;
    }
}

Time Complexity: O(n)

Space Complexity: O(n)

Contributed By: Sumit Chourasia
4Sum - Array - Medium - LeetCode
Contributed By: Sumit Chourasia
Next Permutation - Array - Medium - LeetCode
Contributed By: Sumit Chourasia
Sum of Unique Elements - Array - Easy - LeetCode