重建二叉树

题目

题目:已知某二叉树的前序遍历序列与中序便利序列,请重建该二叉树。假设前序遍历序列与中序遍历序列的结果中不包含重复数字。
前序遍历序列:{1,2,4,7,3,5,6,8}
中序遍历序列:{4,7,2,1,5,3,8,6}

思路

前序遍历就是:根节点——>左子树——>右子树,所以我们可以知道前序遍历序列中的第一个元素就是根节点root
中序遍历就是:左子树——>根节点——>右子树,由于在前序遍历序列中已经找到了根节点root,我们在中序遍历序列中找与根节点值相同的节点,找到之后根节点左面的序列就是左子树,根节点右面的序列就是右子树
假如在中序遍历序列中根节点左面有m个元素,则在前序遍历序列中根节点之后的m个元素就是左子树(按上面的步骤递归处理该子树),之后就全部是右子树(处理方法同左子树)

java代码

package com.cn;

//二叉树结点
class Node{

    int value;
    Node leftTree;
    Node rightTree;

    public Node(){

    }

    public Node(int value){
        this.value = value;
        this.leftTree = null;
        this.rightTree = null;
    }

    public Node(int value, Node leftTree, Node rightTree){
        this.value = value;
        this.leftTree = leftTree;
        this.rightTree = rightTree;
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public Node getLeftTree() {
        return leftTree;
    }

    public void setLeftTree(Node leftTree) {
        this.leftTree = leftTree;
    }

    public Node getRightTree() {
        return rightTree;
    }

    public void setRightTree(Node rightTree) {
        this.rightTree = rightTree;
    }

}

public class BuildTwoForkTree {

    public static void main(String[] args) {
        int[] startPreorder = new int[]{1,2,4,7,3,5,6,8};
        int[] midPreorder = new int[]{4,7,2,1,5,3,8,6};
        Node root = BuildTree(startPreorder,0,startPreorder.length - 1,midPreorder,0,midPreorder.length-1);

        PrintTree(root);
    }
    //根据前序遍历序列及中序遍历序列创建二叉树
    public static Node BuildTree(int[] a,int startA,int endA,int[] b,int startB,int endB){

        if(startA > endA || startB > endB){
            return null;
        }

        Node root = new Node(a[startA]);

        // 在中序遍历序列中寻找根节点
        int i = startB;
        for(;i <= endB;i++){
            if(b[i] == a[startA])
                break;
        }
        //根节点往左是左子树,定义左子树的长度
        int offSet = i - startB;



        //左子树
        root.leftTree = BuildTree(a,startA+1,startA+offSet,b,startB,startB + offSet-1);


        //右子树
        root.rightTree = BuildTree(a,startA+offSet+1,endA,b,startB+offSet+1,endB);


        return root;

    }

    //递归输出二叉树的前序遍历
    public static void PrintTree(Node root){

        if(root == null){
            return; 
        }

        System.out.print(root.value + " ");

        PrintTree(root.leftTree);           
        PrintTree(root.rightTree);

    }

    //非递归输出二叉树的前序遍历
    public static void PrintTree1(Node root){

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值