其他分享
首页 > 其他分享> > 重建二叉树

重建二叉树

作者:互联网

题目描述

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
        return build(pre, in, 0, pre.length-1, 0, pre.length);
    }
    
    public TreeNode build(int [] pre, int [] in, int preL, int preH, int inL, int inH) {
        if (preL > preH) {
            return null;
        }
        TreeNode node = new TreeNode(pre[preL]);
        int k;
        for (k = 0; pre[preL] != in[k]; k++);
        int leftNum = k-inL;
        node.left = build(pre, in, preL+1, preL+leftNum, inL, inL+leftNum-1);
        node.right = build(pre, in, preL+leftNum+1, preH, inL+leftNum+1, inH);
        return node;
    }
}

 

 

iDestro 发布了20 篇原创文章 · 获赞 5 · 访问量 1735 私信 关注

标签:pre,preL,遍历,TreeNode,int,inL,二叉树,重建
来源: https://blog.csdn.net/iDestro/article/details/103996727