106. 從中序與後序遍歷序列構造二叉樹-中等難度
阿新 • • 發佈:2020-07-12
問題描述
根據一棵樹的中序遍歷與後序遍歷構造二叉樹。
注意:
你可以假設樹中沒有重複的元素。
例如,給出
中序遍歷 inorder =[9,3,15,20,7]
後序遍歷 postorder = [9,15,7,20,3]
返回如下的二叉樹:
3
/ \
9 20
/ \
15 7
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal
解答
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * }*/ class Solution { int[] postorder2 = null; int[] inorder2 = null; Map<Integer,Integer> map = null; int len = 0; public TreeNode recursive(int inorder_left,int inorder_right,int postorder_left,int postorder_right){ if(inorder_right-inorder_left<=0)return null;if(inorder_right-inorder_left==1)return new TreeNode(inorder2[inorder_left]); int position = map.get(postorder2[postorder_right-1]); TreeNode r = null; if(position+1<len) r = recursive(position+1,inorder_right,postorder_right-(inorder_right-position),postorder_right-1); TreeNode l= recursive(inorder_left,position,postorder_left,postorder_left+position-inorder_left); return new TreeNode(postorder2[postorder_right-1],l,r); } public TreeNode buildTree(int[] inorder, int[] postorder) { len = inorder.length; if(len==0)return null; postorder2 = postorder; inorder2 = inorder; map = new HashMap<Integer,Integer>(); for(int i=0;i<len;i++) map.put(inorder2[i],i); return recursive(0,len,0,len); } }