Given preorder and inorder traversal of a tree, construct the binary tree.

根据给定的先序遍历({0,1,3,4,7,2,5,8,6})和中序遍历({3,1,7,4,0,5,8,2,6}),利用递归算法,通过找到根节点及其左右子树在两个遍历序列中的位置,逐步构建二叉树结构。" 8890603,642311,回溯法解决旅行员售货与圆排列问题,"['算法', '回溯法', '旅行员售货问题', '圆排列', '搜索算法']

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

题目:利用先序遍历和中序遍历,构造一个二叉树!

例如:

Inorder Traversal:{3,1,7,4,0,5,8,2,6};
Preorder Traversal:{0,1,3,4,7,2,5,8,6};

思路:

1. 先序数组第一个元素为根节点(root);(上例中 root.val= 0)

2. 以root为中心,中序数组分成两个子数组,即为root的左右子树!(上例中分为:subLeft={3,1,7,4}、subRight={5,8,2,6})

3. 在先序序列中 找到对应subLeft在先序数组中的子数组subPreLeft = {1,3,4,7}、

   subRight在先序数组中的字数组subPreRight= {2,5,8,6}

4. 在subPreLeft中的首元素为root.left;

    在subPreRight中的首元素为root.right;

循环上面4个步骤,建立tree!

对应代码:

public static TreeNode buildTreePure(int[] inorder, int[] preorder) {
		if(inorder.length <= 0 && inorder.length != preorder.length) return null;
		int inLeft = 0, preLeft = 0,length = inorder.length;
		TreeNode root = building(inLeft, preLeft, length, inorder, preorder);
        return root;
	}
	
	public static TreeNode building(int inLeft, int preLeft, int length, int[] myIn, int[] myPre){
		if(length>0 && preLeft>=0 && preLeft<myPre.length && inLeft>=0 && inLeft<myIn.length){
			TreeNode root = new TreeNode(myPre[preLeft]);
			
			// get leftLen	
			int leftLen = 0;
			for(int i = inLeft; i < (inLeft+length); i++){
				if(myPre[preLeft] == myIn[i]){
					leftLen = i-inLeft;
//					System.out.println("i =" + i);
					break;
				}
			}
			
			// divide myIn/myPre
			root.left  = building(inLeft,preLeft+1,leftLen, myIn, myPre);
			root.right = building(inLeft+leftLen+1,preLeft+leftLen+1,length-1-leftLen, myIn, myPre);
			return root;
		}
		
		return null;
	}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值