leetcode106/105.从中序与后序(/前序)遍历构造二叉树(java):分治

题目
在这里插入图片描述
代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
   public TreeNode buildTree(int[] inorder, int[] postorder) {
        TreeNode root = helper(inorder,0,inorder.length-1,postorder,0,inorder.length-1);
        return root;
    }
    public TreeNode helper(int[] inorder, int inLeft,int inRight, int[] postorder,int postLeft,int postRight){
        if(inLeft > inRight || postLeft > postRight){
            return null;
        }
        int pivot = postorder[postRight];
        TreeNode root = new TreeNode(pivot);
        int pivotIndex = inLeft;
        while(inorder[pivotIndex] != pivot){
            pivotIndex++;
        }
        root.left = helper(inorder,inLeft,pivotIndex-1,postorder,postLeft,postLeft+(pivotIndex-1-inLeft));
        root.right = helper(inorder,pivotIndex+1,inRight,postorder,postLeft+(pivotIndex-inLeft),postRight-1);
        return root;
    }

}

从中序和前序遍历构造二叉树

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return helper(preorder,0,preorder.length-1,inorder,0,inorder.length-1);
    }
    public TreeNode helper(int[] preorder,int preLeft,int preRight,int[] inorder,int inLeft, int inRight){
        if(preLeft > preRight || inLeft > inRight){
            return null;
        }
        int pivot = preorder[preLeft];
        TreeNode root = new TreeNode(pivot);
        int pivotIndex = inLeft;
        while(inorder[pivotIndex] != pivot){
            pivotIndex++;
        }
        root.left = helper(preorder,preLeft+1,preLeft+(pivotIndex-inLeft),inorder,inLeft,pivotIndex-1);
        root.right = helper(preorder,preLeft+(pivotIndex-inLeft)+1,preRight,inorder,pivotIndex+1,inRight);
        return root;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值