04-面试题7--重建二叉树

package com.my.util;
/**
 * 二叉树的节点
 * */
public class TreeNode {
	public int value;
	public TreeNode left;
	public TreeNode right;
	public TreeNode(int data) {
		this.value = data;
	}
}

已知先序和中序序列,重建二叉树

package com.my.offer;

import com.my.util.TreeNode;

/**
 * 重建二叉树:已知先序和中序序列
 * @author asus
 *
 */
public class Solution04 {
	/**
	 * 已知先序和中序,重建二叉树
	 * @param pre
	 * @param in
	 * @return
	 */
	public TreeNode rebuildBinaryTree(int[] pre, int[] in) {
		//边界条件判断
		if(pre == null || in == null) {
			return null;
		}
		//递归的找到二叉树的根节点,并将根节点返回
		TreeNode root = rebuildBinaryTree(pre, 0, pre.length - 1, in, 0, in.length - 1);
		return root;
	}
	/**
	 * 根据先序和中序找到根节点和左右子树
	 * @param pre
	 * @param startP
	 * @param endP
	 * @param in
	 * @return
	 */
	private TreeNode rebuildBinaryTree(int[] pre, int startP, int endP, int[] in, int startI, int endI) {
		//递归结束条件
		if(startP > endP || startI > endI) {
			return null;
		}
		//根据先序序列找到根节点
		TreeNode root = new TreeNode(pre[startP]);
		//遍历中序序列,找到该根节点的左子树和右子树
		for(int i = startI; i <= endI; i++) {
			if(in[i] == pre[startP]) {
				//说明下标i对应的元素为根节点,i左边为左子树,i右边为右子树
				root.left = rebuildBinaryTree(pre, startP + 1, startP + (i - startI), in, startI, i - 1);
				root.right = rebuildBinaryTree(pre, startP + (i - startI) + 1, endP, in,  i + 1, endI);
			}
		}
		return root;
	}
}

已知中序和后序序列,重建二叉树

package com.my.offer;

import com.my.util.TreeNode;

/**
 * 重建二叉树:已知中序后后序序列
 * @author asus
 *
 */
public class Solution05 {
	/**
	 * 已知先序和中序,重建二叉树
	 * @param in
	 * @param post
	 * @return
	 */
	public TreeNode rebuildBinaryTree(int[] in, int[] post) {
		//边界条件判断
		if(in == null || post == null) {
			return null;
		}
		//递归的找到二叉树的根节点
		TreeNode root = rebuildBinaryTree(in, 0, in.length - 1, post, 0, post.length - 1);
		return root;
	}
	private TreeNode rebuildBinaryTree(int[] in, int startI, int endI, int[] post, int startP, int endP) {
		//递归结束条件
		if(startI > endI || startP > endP) {
			return null;
		}
		//根据后序序列找到根节点
		TreeNode root = new TreeNode(post[endP]);
		//遍历中序序列,找到该根节点的左子树和右子树
		for(int i = startI; i <= endI; i++) {
			if(in[i] == post[endP]) {
				//说明i下标对应的元素是根节点,该下标左边为左子树,该下标右边为右子树
				root.left = rebuildBinaryTree(in,startI, i - 1, post, startP, startP + (i - startI) - 1);
				root.right = rebuildBinaryTree(in,i + 1, endI , post, startP + (i - startI), endP  - 1);
			}
		}
		return root;
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值