(剑指offer)重建二叉树
来源:互联网 发布:信用卡网络推广合作 编辑:程序博客网 时间:2024/05/17 18:43
题目描述:
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
代码如下:
public class ReConstructBinaryTree { public TreeNode reConstructBinaryTree(int[] pre, int[] in) { TreeNode root = null; if (pre == null || in == null) { return null; } root = constructBinaryTree(pre, 0, pre.length - 1, in, 0, in.length - 1); return root; } public TreeNode constructBinaryTree(int[] pre, int preStr, int preEnd, int[] in, int inStr, int inEnd) { if (preStr > preEnd || inStr > inEnd) { return null; } // 前序遍历的第一个结点为二叉树的根节点 TreeNode root = new TreeNode(pre[preStr]); // 记录每次根节点所在位置 int index = 0; for (; index < inEnd; index++) { if (in[index] == pre[preStr]) { break; } } // 递归调用求得根节点的左子树 root.left = constructBinaryTree(pre, preStr + 1, preStr + index - inStr, in, inStr, index - 1); // 递归调用求得根节点的右子树 root.right = constructBinaryTree(pre, preStr + index - inStr + 1, preEnd, in, index + 1, inEnd); return root; }}
阅读全文
0 0
- 剑指offer(5):重建二叉树
- 重建二叉树(剑指offer)
- 剑指offer(四)重建二叉树
- (剑指offer)重建二叉树
- 剑指offer--(4) 重建二叉树
- 剑指offer---重建二叉树(6)
- 剑指Offer(四)重建二叉树
- [剑指offer]重建二叉树
- 【剑指offer】重建二叉树
- 剑指offer--重建二叉树
- 剑指offer---重建二叉树
- 剑指Offer-重建二叉树
- 剑指offer:重建二叉树
- 剑指offer-重建二叉树
- 《剑指offer》重建二叉树
- 【剑指Offer】重建二叉树
- 剑指offer-重建二叉树
- 《剑指offer》-重建二叉树
- 挑战程序竞赛系列(68):4.7字符串匹配(3)
- 最新datetimepicker用法总结
- 使用RecyclerView实现时间轴
- CODE[VS]1025 选菜
- 标准机器学习数据集
- (剑指offer)重建二叉树
- Fred 7.0.0 光线追迹软件_USB加密锁,全模块运行稳定版\
- 客户端与服务器端交互原理
- Hrbust 2210 A Wonderful Concert【Dp】水题
- XListView的上拉加载和下拉刷新
- spring和cookie
- JAVA设计模式:状态模式
- 新员工转正申请书如何写呢?工作转正申请书范文分享
- hdu2883 kebab(判满流)