(4)重新二叉树
1.题目
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
2.思路
(1)由先序可知,当前第一个元素A的是当前前子树的根节点
(2)从中序查找A,A前面的元素都是当前的左子树,A右边的元素都是右子树
3.代码
package test1_10;
/* * @author qianliu on 2019/3/31 10:41 * @Discription: * 1.问题:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。 * 假设输入的前序遍历和中序遍历的结果中都不含重复的数字。 * 例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。 */
public class test4 {
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};
TreeNode node = new test4().reConstructBinaryTree(pre, in);
new test4().printTree(node);
}
//树的节点
public class TreeNode{
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
/* * @author qianliu on 2019/3/31 10:44 * @param pre为前序序列 * in为中序序列 * @return tree是树的根节点 * @Discription: * 1.问题:根据前序和中序遍历构建一棵二叉树 */
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
//输入合法性判断, 不能为空,先序和后序长度要一致
if(pre == null || in == null || pre.length != in.length)
return null;
return construct(pre, 0, pre.length-1, in, 0, in.length-1);
}
/** * * @param pre 前序遍历 * @param ps 前序遍历的开始位置 * @param pe 前序遍历的结束位置 * @param in 中序遍历 * @param is 中序遍历的开始位置 * @param ie 中序遍历的结束位置 * @return 树的根节点 */
private TreeNode construct(int[] pre, int ps, int pe, int[] in, int is, int ie){
//判断退出的条件
if (ps > pe) return null;
//前序的第一个节点解释当前的根节点
int value = pre[ps];
//在中序节点中找出根节点
int index = is;
for (; index < ie ; index++) {
if (value == in[index]){
break;
}
}
// 创建当前根节点,并为根节点赋值
TreeNode node = new TreeNode(value);
// 递归调用构建当前节点的左子树
node.left = construct(pre, ps+1, ps+index-is, in, is, index-1);//index-is表示左子树的所有元素个数
// 递归调用构建当前节点的右子树
node.right = construct(pre, ps+index-is+1, pe, in, index+1, ie);
return node;
}
//打印树
private void printTree(TreeNode root) {
if(root != null) {
printTree(root.left);
System.out.println(root.val + " ");
printTree(root.right);
}
}
}