105 重建二叉树

image.png

思路

  1. 主要解题思路,使用递归的方法<br /> 1、前序遍历中第一个元素对应根节点(递归思路,每次都是根节点)<br /> 2、根节点在中序遍历中每次将中序遍历平分为两分,左边和右边分别对应一个新的子树<br /> 3、递归中止条件,当根节点再往下分子树,子树为空即结束递归

code

  1. class Solution {
  2. public TreeNode buildTree(int[] preorder, int[] inorder) {
  3. int start = 0;
  4. int end = preorder.length-1;
  5. return buildTreeStep(start,end,start,end,preorder,inorder);
  6. }
  7. //递归实现
  8. public TreeNode buildTreeStep(int preStart ,int preEnd ,int inStart,int inEnd,int[] preorder,int[] inorder){
  9. if (preEnd<preStart || inEnd<inStart) {
  10. return null;
  11. }
  12. TreeNode treeNode = new TreeNode(preorder[preStart]);
  13. int pivot = getCurIndexInInOrder(inorder,inStart,inEnd,preorder[preStart]);
  14. treeNode.left = buildTreeStep(preStart+1,pivot+preStart,inStart,inStart+pivot-1,preorder,inorder);
  15. treeNode.right = buildTreeStep(preStart+pivot+1,preEnd,inStart+pivot+1,inEnd,preorder,inorder);
  16. return treeNode;
  17. }
  18. //get pivot index
  19. public int getCurIndexInInOrder(int[] inorder, int start, int end, int key){
  20. for(int i=start; i<=end; i++){
  21. if(inorder[i] == key) return i-start;
  22. }
  23. return -1;
  24. }
  25. }