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

leetcode 重建二叉樹

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        int size = preorder.length;
        if(size == 0)
            return null;
        return help(preorder, inorder, 0, size - 1, 0, size - 1);
    }
    public TreeNode help(int[] preorder, int[] inorder, int pleft, int pright, int ileft, int
iright) { if(pleft > pright || ileft > iright) return null; TreeNode root = new TreeNode(preorder[pleft]); int i; for(i = ileft; i <= iright; i++){ if(inorder[i] == preorder[pleft]) break; } root.left = help(preorder, inorder,pleft + 1
, pleft + i - ileft, ileft, i - 1); root.right = help(preorder, inorder,pleft + i - ileft + 1, pright, i + 1, iright); return root; }
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        int size = inorder.length;
        if(size == 0)
            return null
; return help(inorder, postorder, 0, size - 1, 0, size - 1); } public TreeNode help(int[] inorder, int[] postorder, int ileft, int iright, int pleft, int pright) { if(pleft > pright || ileft > iright) return null; TreeNode root = new TreeNode(postorder[pright]); int i; for(i = ileft; i <= iright; i++){ if(inorder[i] == postorder[pright]) break; } root.left = help(inorder, postorder,ileft, i - 1, pleft, pleft + i - ileft - 1); root.right = help(inorder, postorder,i + 1, iright, pleft + i - ileft, pright - 1); return root; }