根据一棵树的中序遍历与后序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
中序遍历 inorder = [9,3,15,20,7] 后序遍历 postorder = [9,15,7,20,3]
返回如下的二叉树:
3 / \ 9 20 / \ 15 7
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public TreeNode buildTree(int[] arr, int[] brr) { return DFS(brr,0,arr,0,arr.length); } TreeNode DFS(int []brr,int i,int []arr ,int j, int n){ if(n==0) return null; TreeNode now =new TreeNode(brr[i+n-1]); int count=0; while(count<n){ if(arr[j+count]==brr[n-1+i]) break; count ++; } now.left=DFS(brr,i,arr,j,count); now.right=DFS(brr,i+count,arr,j+count+1,n-count-1); return now; } }