leetcode 106從中序與後序遍歷序列構造二叉樹
阿新 • • 發佈:2021-09-04
根據一棵樹的中序遍歷與後序遍歷構造二叉樹。
注意:
你可以假設樹中沒有重複的元素。
例如,給出
中序遍歷 inorder =[9,3,15,20,7]
後序遍歷 postorder = [9,15,7,20,3]
返回如下的二叉樹:
連結:https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal
這個題目跟105題目的思路是一樣的,不同的是這裡使用的後續遍歷序列,那麼把後續反序之後就是:中序遍歷左右子樹交換的結果
public TreeNode buildTree(int[] inorder, int[] postorder) { if(inorder.length==0) return null; HashMap<Integer,Integer> inorderMap=new HashMap<>(); for(int i=0;i<inorder.length;i++) { inorderMap.put(inorder[i],i); } return posBuild(inorder,postorder,inorderMap,0,inorder.length-1,0,postorder.length-1); } public TreeNode posBuild(int[] inorder, int[] postorder,HashMap<Integer,Integer> inorderMap,int inorderLeft,int inorderRight,int postLeft,int postRight) { if(postLeft>postRight) return null; int rootIndex=postRight; int inorderRottIndex=inorderMap.get(postorder[rootIndex]); TreeNode root=new TreeNode(postorder[rootIndex]); int rightCount=inorderRight-inorderRottIndex; root.right=posBuild(inorder,postorder,inorderMap,inorderRottIndex+1,inorderRight,postRight-rightCount,postRight-1); root.left=posBuild(inorder,postorder,inorderMap,inorderLeft,inorderRottIndex-1,postLeft,postRight-rightCount-1); return root; }