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

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

1 min read 187 words
1 min read
ShareWhatsAppPost on X
  • 1The article explains how to construct a binary tree using inorder and postorder traversal arrays.
  • 2It provides a sample input with inorder and postorder arrays to illustrate the tree construction.
  • 3The solution has a time complexity of O(n) and a space complexity of O(n).

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The article explains how to construct a binary tree using inorder and postorder traversal arrays."

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)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 17 November 2020 · 1 min read · 187 words

Part of AskGif Blog · coding

You might also like