刷题小记 (36) LeetCode 106 从中序与后序遍历序列构造二叉树

LeetCode 106

2020.9.26

我的通过代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int[] in;
    int[] post;
    TreeNode node = null;
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        in = inorder;
        post = postorder;
        node = create(0,inorder.length-1,0,postorder.length-1);
        return node;

    }

    public TreeNode create(int beginInorder,int endInorder,int beginPostorder,int endPostorder) {
        int length = endInorder - beginInorder + 1; //数组长度
        if(length <= 0) return null;
        TreeNode root = new TreeNode(post[endPostorder]);
        int pos = getIndex(in,root.val);
        root.left = create(beginInorder,pos-1,beginPostorder,beginPostorder+pos-beginInorder-1);
        root.right = create(pos+1,endInorder,beginPostorder+pos-beginInorder,endPostorder-1);
        return root;
    }

    public int getIndex(int[] arr, int val) {
        for(int i=0;i<arr.length;i++) {
            if(arr[i] == val) {
                return i;
            }
        }
        return -1;
    }
}

这道题我遇到了一个的问题和小记36里的一样,这两题也是隔天做的,问题是一起解决的,还是java函数的参数传递问题,解决方法相同,错误的代码如下:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int[] in;
    int[] post;
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        in = inorder;
        post = postorder;
        TreeNode node = null;
        create(0,inorder.length-1,0,postorder.length-1,node);
        return node;

    }

    public void create(int beginInorder,int endInorder,int beginPostorder,int endPostorder,TreeNode node) {
        int length = endInorder - beginInorder + 1; //数组长度
        if(length <= 0) return;
        node = new TreeNode(post[endPostorder]);
        System.out.println(node.val);
        int pos = getIndex(in,node.val);
        create(beginInorder,pos-1,beginPostorder,beginPostorder+pos-beginInorder-1,node.left);
        create(pos+1,endInorder,beginPostorder+pos-beginInorder,endPostorder-1,node.right);
    }

    public int getIndex(int[] arr, int val) {
        for(int i=0;i<arr.length;i++) {
            if(arr[i] == val) {
                return i;
            }
        }
        return -1;
    }
}

©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页