刷题小记 (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;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值