LeetCode--105/106. Construct Binary Tree from Inorder/Preorder and Postorder Traversal
阿新 • • 發佈:2018-12-17
這兩個題目思路如出一轍,演算法原來也寫過詳細的部落格,參考這兩個1.https://blog.csdn.net/To_be_to_thought/article/details/84668630
2.https://blog.csdn.net/To_be_to_thought/article/details/84674266
程式碼集中貼一下:
class Solution { public TreeNode buildTree(int[] preorder, int[] inorder) { return recursion(inorder,preorder,0,0,inorder.length); } public static TreeNode recursion(int[] inorder,int[] preorder,int preStart,int inStart,int n) { if(n<=0) return null; int rootValue=preorder[preStart]; TreeNode p=new TreeNode(rootValue); int i=0; while(i<n && inorder[i+inStart]!=rootValue) i++; p.left=recursion(inorder,preorder,preStart+1,inStart,i); p.right=recursion(inorder,preorder,preStart+i+1,inStart+i+1,n-1-i); return p; } }
class Solution { public static TreeNode buildTree(int[] inorder, int[] postorder) { return recursion(inorder,postorder,0,0,inorder.length); } public static TreeNode recursion(int[] inorder,int[] postorder,int inStart,int postStart,int n) { if(n<=0) return null; int rootValue=postorder[postStart+n-1]; TreeNode p=new TreeNode(rootValue); int i=0; while(i<n && inorder[i+inStart]!=rootValue) i++; p.left=recursion(inorder,postorder,inStart,postStart,i); p.right=recursion(inorder,postorder,inStart+i+1,postStart+i,n-i-1); return p; } }