重建二叉树
问题描述:已知前序和中序遍历结果,重构二叉树(不存在重复数据)。
本方法思想:前序遍历的第一个遍历是根,找到中序中的根所在的位置loc;在中序遍历中,在loc之前的是左子树,之后的是右子树(中序遍历的性质),递归的去重建左子树和右子树。
持续更新...
代码附下
Java实现:
package 重建二叉树;
/**
* 已知前序和中序遍历结果,重构二叉树
* 前序的第一个是根,找到中序中的根所在的位置,
* 前面的的是左子树,后面的是右子树
* 递归下去
* @author user
*/
class TreeNode {
public int value;
public TreeNode leftNode;
public TreeNode rightNode;
}
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] pre = { 1, 2, 4, 7, 3, 5, 6, 8 };
int[] in = { 4, 7, 2, 1, 5, 3, 8, 6 };
printTree(Constuct(pre, 0, pre.length - 1, in, 0, in.length - 1));
System.out.println();
printTree2(Constuct(pre, 0, pre.length - 1, in, 0, in.length - 1));
}
private static TreeNode Constuct(int[] pre, int preStart, int preEnd, int[] in, int inStart, int inEnd) {
if (preStart > preEnd) {// 開始元素比結束元素大就沒有了
// System.out.println("输入不合法!");
return null;
}
if (preStart == preEnd) {
TreeNode root = new TreeNode();
root.value = pre[preStart];
return root;
}
int index = -1;
// 找到每次的根是在中序遍歷中是哪個
for (int i = inStart; i <= inEnd; i++) {
if (in[i] == pre[preStart]) {
index = i;
break;
}
}
// 创建当前的根节点,当前根节点就是前序遍历的第一个
TreeNode root = new TreeNode();
root.value = pre[preStart];
// 递归构建左子树
// 左子树元素个数为ln=index-inStart
// 左子树前序遍历位置[preStart+1,preStart+index-inStart]
// 左子树对应的中序遍历位置[inStart,index-1]
root.leftNode = Constuct(pre, preStart + 1, preStart + index - inStart, in, inStart, index - 1);
/**
* 递归构建右子树 右子树前序遍历位置【preStart+index-inStart+1,preEnd】
* 右子树中序遍历位置【index+1,inEnd】
*/
root.rightNode = Constuct(pre, preStart + index - inStart + 1, preEnd, in, index + 1, inEnd);
return root;
}
// 中序遍历
public static void printTree(TreeNode root) {
if (root != null) {
printTree(root.leftNode);
System.out.print(root.value + " ");
printTree(root.rightNode);
}
}
// 前序遍历
public static void printTree2(TreeNode root) {
if (root != null) {
System.out.print(root.value + " ");
printTree2(root.leftNode);
printTree2(root.rightNode);
}
}
}
持续更新...欢迎赞赏!![](https://i-blog.csdnimg.cn/blog_migrate/ca0cc5c488ad24501c0bbddad6302b17.png)
https://blog.csdn.net/ustcer_93lk/article/details/80367615
如果有问题,欢迎大家留言,有更好的方法也期待大家告知。