LeetCode105. 从前序与中序遍历序列构造二叉树

问题描述

 解题思路:

前序遍历root节点在数组最前面,所以前序遍历的数组第一个就是root节点,找到root节点,遍历中序遍历的数组,找到root节点在中序遍历数组的index。中序遍历找到root节点位置,root节点左右就是root节点的左/右子树。index-中序遍历的其实值就是左子树的个数(leftSize)。有leftSize数组中左子树边界,右子树边界,root节点index全都已知。可以递归构建二叉树了。

代码实例:
 

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return build(preorder,0,preorder.length-1,inorder,0,inorder.length-1);
    }
    TreeNode build(int[]preorder,int preLeft,int preRight,int[]inorder, int inLeft,int inRight){
         if (preLeft > preRight) {
        return null;
    }
        int rootVal = preorder[preLeft];
        int index = -1;
        for(int i = inLeft;i<=inRight;i++){
            if(rootVal == inorder[i]){
                index = i;
                break;
            }
        }
        TreeNode node = new TreeNode(rootVal);
        int leftSize = index-inLeft;
        node.left = build(preorder,preLeft+1,preLeft+leftSize,inorder,inLeft,index-1);
        node.right = build(preorder, preLeft + leftSize + 1, preRight,inorder, index + 1, inRight);
        return node;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值