剑指offer 6. 重建二叉树

class BinaryTreeNode {
	int value;
	BinaryTreeNode leftNode;
	BinaryTreeNode rightNode;
}

// 题目:输入两个数组,分别是二叉树的前序和中序遍历结果,输出结果二叉树
// 解法:从每个节点进行构建,找到前序遍历每个根节点在中序遍历的位置,递归的构建树
public class Main {
	
	public static void main(String[] args) throws Exception {
		BinaryTreeNode result = buildBinaryTree(new int[]{1,2,4,7,3,5,6,8}, new int[]{4,7,2,1,5,3,8,6});
		preOrder(result);
		System.out.println("complete!");
	}
	
	public static BinaryTreeNode buildBinaryTree(int[] preOrder, int[] inOrder){
		if(preOrder.length == 0 || inOrder.length == 0){
			return null;
		}
		int value = preOrder[0];
		int cut = 0;
		for(int i = 0;i<inOrder.length;i++){
			if(inOrder[i] == value){
				cut = i;
				break;
			}
		}
		BinaryTreeNode root = new BinaryTreeNode();
		root.value = value;
		root.leftNode = buildBinaryTree(Arrays.copyOfRange(preOrder, 1, cut+1),Arrays.copyOfRange(inOrder, 0, cut));						//重建左子树
		root.rightNode = buildBinaryTree(Arrays.copyOfRange(preOrder, cut+1, preOrder.length), Arrays.copyOfRange(inOrder, cut+1,inOrder.length));	//重建右子树
		return root;
	}
	
	//检查结果用的
	public static void preOrder(BinaryTreeNode root){
		Stack<BinaryTreeNode> s = new Stack<BinaryTreeNode>();
		while(root!=null || !s.isEmpty()){
			if(root!=null){
				s.push(root);
//				System.out.print(root.value+" ");					//非递归前序遍历
				root = root.leftNode;
				continue;
			}else{
				root = s.pop();
				System.out.print(root.value+" ");					//非递归中序遍历
				root = root.rightNode;
			}
		}
	}
	
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值