Given Inorder and Postorder traversal of a tree, construct the binary tree.
Note:
Assume that duplicates does not exist in the tree.
Idea: This problem is similar to the previous one, the first is the root node, and the last is the root node of the post-order traversal. The rest of the steps are similar.
The code is as follows:
/** * Definition for a binary tree node. * public class TreeNode {* int val, * TreeNode left, * TreeNode right; * TreeNode (int x) {val = x;} *} */public class Solution {public TreeNode buildtree (int[] inorder, int[] postorder) {/** * 1. According to the post-post traversal, first Determine the root node * 2. Then find the root node in the middle sequence traversal, and determine the location of the root node in the middle order traversal * 3. Segmentation of the left and right subtree based on the index location * 4. Recursively solves the left and right subtree of the root node */ if (Postorder.length = = 0 | | inorder.length = = 0) return null; TreeNode root = new TreeNode (postorder[postorder.length-1]); int k = 0; for (; k < inorder.length; k++) {if (inorder[k] = = Postorder[postorder.length-1]) {break; }} int[] P1 = Arrays.copyofrange (postorder,0,k); int[] q1 = arrays.copyofrange (postorder,k,postorder.length-1); int[] P2 = arrays.copyofrange (inorder,0,k); int[] q2 = Arrays.copyofrange (inorder,k+1,inorder.length); Root.left = Buildtree (P2,P1); Root.right = Buildtree (Q2,Q1); return root; }}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode 106.Construct binary tree from Inorder and Postorder traversal (based on the middle sequence traversal and post-order traversal constructs two fork trees)