//题目:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。 // 假设输入的前序遍历和中序遍历的结果中都不含重复的数字。 // 例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。 //解题思路: // 1)根据前序遍历序列确定根节点: // 在前序遍历序列中,第一个数字总是根的节点值。 // 2)根据中序遍历序列确定左、右子树的节点: // 在中序遍历序列中,根节点的值在序列的中间,左子树的节点的值位于根节点的值的左边, // 而右子树的节点的值位于根节点的值的右边。 // // // public class P62_reConstructBinaryTree { public TreeNode reConstructBinaryTree(int[] pre, int[] in) { if (pre == null || in == null || pre.length <= 0 || in.length <= 0 || pre.length != in.length) { return null; } return ReConstructTree(pre, in, 0, pre.length - 1, 0, in.length - 1); } public TreeNode ReConstructTree(int[] pre, int[] in, int pStart, int pStop, int iStart, int iStop) { //根节点 int rootValue = pre[pStart]; TreeNode root = new TreeNode(rootValue); root.left = null; root.right = null; //递归终止条件b boolean a = (pStart == pStop); boolean b = (iStart == iStop); if (a && b) { return root; } /** * if (pStart == pStop) { if (iStart == iStop) { System.out.print(rootValue); return root; }else{ System.out.println("输入的两个序列长度不一致"); return null; } } */ //在中序序列寻找根节点 int iRoot = iStart; while (in[iRoot] != rootValue && iRoot<=iStop) { ++iRoot; } if (in[iRoot] != rootValue) { return null; } //在中序序列中寻找到根节点,移动的长度 int iLength = iRoot - iStart; //重建左子树 if (iRoot > iStart) { root.left = ReConstructTree(pre, in, pStart + 1, pStart + iLength, iStart, iRoot - 1); } //重建右子树 if (iRoot < iStop) { root.right=ReConstructTree(pre,in,pStart+iLength+1,pStop,iRoot+1,iStop); } return root; } public static void main(String[] args) { int[] pre = {1, 2, 4, 7, 3, 5, 6, 8}; int[] in = {4, 7, 2, 1, 5, 3, 8, 6}; P62_reConstructBinaryTree test = new P62_reConstructBinaryTree(); TreeNode BinaryTree = test.reConstructBinaryTree(pre, in); } }
剑指offer:重建二叉树(java)
猜你喜欢
转载自blog.csdn.net/Sunshine_liang1/article/details/82562874
今日推荐
周排行