剑指Offer之重建二叉树

题目:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如:前序遍历序列{ 1, 2, 4, 7, 3, 5, 6, 8}和中序遍历序列{4, 7, 2, 1, 5, 3, 8,6},重建出下图所示的二叉树并输出它的头结点。

在这里插入图片描述
思路:
前序序列:【1 2 4 7 3 5 6 8】 中序序列:【4 7 2 1 5 3 8 6】

从前序遍历序列观察到根节点为1,结合中序序列得到:
左子树元素:【4 7 2 1】 右子树元素:【5 3 8 6】
左子树:前序遍历序列:【2 4 7】 中序遍历序列:【4 7 2】
右子树:前序遍历序列:【3 5 6 8】 中序遍历序列:【5 3 8 6】
然后根据左子树的前序遍历序列和中序遍历序列重复上述操作;
然后根据右子树的前序遍历序列和中序遍历序列重复上述操作;

代码参考:

1、定义二叉树树节点

class TreeNode{
   public int value;
   public TreeNode leftChild;
   public TreeNode rightChild;
   public TreeNode(int value) this.value = value;
}

2、定义核心函数

public TreeNode construct(int[] preOrder, int[] inOrder){
 if(preOrder == null || preOrder.length == 0 || inOrder == null || inOrder.length == 0) return null;
   return construct(preOrder,0,preOrder.length - 1,inOrder,0,inOrder.length - 1);
}
public TreeNode construct(int[] preOrder,int ps,int pe,int[] inOrder ,int is,int ie){
  
   if(ps > pe || is > ie) return null;
   //获取根节点
   int value= preOrder[ps];
   int index = is;
   //创建结点
   TreeNode node = new TreeNode(value);
   //从中序序列查找等于index的序号
   while(index < ie && inOrder[index] != value)index ++;
   if(index > ie) throw new RuntimeException("Input error!");
   //左孩子
   node.leftChild = construct(preOrder , ps + 1 , ps + index - is , inOrder, is, index - 1);
   //右孩子
   node.rightChild = construct(preOrder,ps + index - is + 1 , pe,inOrder, index + 1, ie);
  return node;
}

参考文章:https://blog.csdn.net/derrantcm/article/details/45457557

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值