根据遍历序列重建二叉树

根据给定的二叉树前序和中序遍历序列,可以重建二叉树。文章详细介绍了如何利用这两个序列来构建二叉树的步骤,并指出与后序遍历结合重建的相似之处。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。

1)根据前序、中序遍历重建二叉树

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public  TreeNode reConstructBinaryTree(int [] pre,int [] in) {
        TreeNode t = createTree(pre, in, 0, 0, in.length);
        
        return t;
    }
	
	public static TreeNode createTree ( int [] pre, int [] in, int i, int low, int high) {
		// i 为当前的树根节点在前序遍历数组的位置
		// [low, high) 表示当前处理的树所有节点在中序数组中的分布范围
		TreeNode t = new TreeNode(pre[i]);
		// index 是当前树的根节点在中序遍历数组中的位置
		
		int index = low;
		for ( ; index < high; index++ ) {
			if ( in[index] == pre[i] ) 
				break;
		}
		
		if( index - 1 >= low ) {
			t.left = createTree(pre, in, i+1, low, index);
		}
		else {
			t.left = null;
		}
		
		if ( index + 1 < high) {
			t.right = createTree(pre, in, i + index - low + 1, index + 1, high);
		}
		else {
			t.right = null;
		}
		
		return t;
	}
}

2) 根据后序遍历和中序遍历重建二叉树,原理差不多

BTree createTree2 ( int *post, int *in, int i, int low, int high ) {
    int index;
    BTree t = (BTree)malloc(sizeof(BinaryTree));
    t->value = post[i];

    index = low;
    for ( ; index < high; index++ ) {
        if ( in[index] == post[i] ) {
            break;
        }
    }

    if ( index - 1 >= low ) {
        t->leftChild = createTree2(post, in, i - high + index, low, index);
    }
    else {
        t->leftChild = NULL;
    }

    if ( index + 1 < high ) {
        t->rightChild = createTree2(post, in, i - 1, index + 1, high);
    }
    else {
        t->rightChild = NULL;
    }

    return t;
}

BTree reConstructBTree2 ( int *post, int *in, int n ) {
    return createTree2(post, in, n - 1, 0, n);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值