1. 程式人生 > >6 重建二叉樹

6 重建二叉樹

1、遞迴的寫法:

public class Solution {
    public TreeNode reConstructBinaryTree(int [] pre,int plow,int phigh,int [] in,int ilow,int ihigh) {
        if(plow == phigh)
            return new TreeNode(pre[plow]);
        if(plow > phigh || ilow > phigh)
            return null;

        int key = pre[plow];
        TreeNode root = new
TreeNode(key); //找到前序遍歷中的節點在中序遍歷中的位置 int i; for(i=ilow;i<=ihigh;i++){ if(in[i] == key){ break; } } int leftTreeSize = i - ilow; root.left = reConstructBinaryTree(pre,plow+1,plow+leftTreeSize,in,ilow,i-1); root.right = reConstructBinaryTree(pre,plow+leftTreeSize+1
,phigh,in,i+1,ihigh); return root; } public TreeNode reConstructBinaryTree(int [] pre,int [] in) { return reConstructBinaryTree(pre,0,pre.length-1,in,0,in.length-1); } }

有人找i值使用了HashMap來儲存!
注意:終結條件!
if(plow == phigh)
return new TreeNode(pre[plow]);
if(plow > phigh || ilow > phigh)
return null;


尤其是if(plow > phigh || ilow > phigh)條件,陣列下標+1或者-1或者其他變化的時候,肯定不會在你期望的地方結束的。

public class Solution {
     public int indexOfIn(int head,int[] in){
        int len = in.length;
        for(int i=0;i<len;i++)
            if(head == in[i])
                return i;
        return -1;
    }
    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
        int len = in.length;
        if(len == 0)
            return null;
        int head = pre[0];
        TreeNode root = new TreeNode(head);

        int headIndex = indexOfIn(head,in);//3
        int leftLen = headIndex;//3
        int rightLen = len - 1 - headIndex;//4
        int[] leftPre = new int[leftLen];
        int[] rightPre = new int[rightLen];
        for(int i=0;i<leftLen;i++){//3
            leftPre[i] = pre[i+1];
        }
        for(int i=0;i<rightLen;i++){//4
            rightPre[i] = pre[i+headIndex+1];
        }

        int[] leftIn = new int[leftLen];
        int[] rightIn = new int[rightLen];
        for(int i=0;i<leftLen;i++){
            leftIn[i] = in[i];
        }
        for(int i=0;i<rightLen;i++){
            rightIn[i] = in[i+headIndex+1];
        }
        root.left = reConstructBinaryTree(leftPre,leftIn);
        root.right = reConstructBinaryTree(rightPre,rightIn);
        return root;
    }
}

這樣,最後的判斷就簡單了,只需要判斷陣列的長度是不是0即可!