Title Description:
Given Inorder and Postorder traversal of a tree, construct the binary tree.
Note:
Assume that duplicates does not exist in the tree.
is the input sequence traversal (left and right) and post-order traversal (left and right) sequences, resulting in a two-fork tree.
Ideas:
Set Ifrom, ITo respectively inorder start and stop index; PFROM, PTO is the starting and terminating index of postorder in the recursive process.
1. Each time the last node of the post-post traversal is taken as the current root node, that is, present = new TreeNode (postorder[len-1])
2. Index of postorder[len-1] found from the inorder sequence, as index
3. Create Zuozi: Inorder's Index range: [0,index), Postorder's index range: [Pfrom, Pfrom + distance (index, IFrom)-1).
4. Create right subtree: Index range for inorder: [index + 1, Len], postorder index range: [Pfrom + distance (index, iFrom), PTo-1].
Termination conditions: pfrom > PTo or Ifrom > ITo
Implementation code:
/** * Definition for a binary tree node. * public class TreeNode {* public int val, * public TreeNode left, * public TreeNode right, public Tree Node (int x) {val = x;} *} */public class Solution {public TreeNode buildtree (int[] inorder, int[] postorder) {TreeN Ode node = Null;var len = postorder. Length-1; Build (ref node, inorder, 0, Len, postorder, 0, Len); return node;} private void Build (ref TreeNode Current, int [] inorder, int iFrom, int iTo, int[] postorder, int pfrom, int pTo) {if (iFrom > ITo | | Pfrom > PTo) {return;} Set currentcurrent = new TreeNode (Postorder[pto]);//Take the last one from post order, because it is the Rootvar pLas t = postorder[pto];//find its index in Inordervar index = -1;for (var i = ifrom;i <= iTo; i++) {if (inorder[i] = = PLast) { index = I;break;}} For left Sub tree, inorder: [0, index]. Postorder: [Pfrom, Pfrom + distance (index, IFrom)-1) Build (ref current.left, Inorder, IFrom, Index-1, Postorder, Pfrom , Pfrom + IndeX-IFROM-1);//For Right Sub tree, inorder: [index + 1, Len], postorder: [Pfrom + distance (index, iFrom), Pto-1]buil D (ref current.right, inorder, index + 1, iTo, Postorder, Pfrom + Index-ifrom, pTo-1);}}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode--Construct Binary Tree from inorder and Postorder traversal