题目描述:
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
解题思路:
1.根据二叉树的先根遍历可以知道此二叉树的根节点。
2.根据二叉树根节点在中序遍历中的位置,可以将中序遍历中根节点之前的节点作为根节点的左子树,之后的节点作为右子树。(也就是获得了根节点左右子树的中根遍历)
3.根据左右子树的长度可以从二叉树的先根遍历中获得左右子树的先根遍历。
4.已经知道了左右子树的先根遍历、中根遍历后,再把他们重建为二叉树即可。
代码:
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.ArrayList;
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
if(pre.length == 0 || in.length == 0)
{
return null;
}
TreeNode RootNode = new TreeNode(pre[0]);
if(pre.length == 1)
{
return RootNode;
}
//获得左右子树中根遍历
ArrayList inLeftChildTree = new ArrayList<Integer>();
ArrayList inRightChildTree = new ArrayList<Integer>();
boolean isLeft = true;
for(int i = 0; i < in.length; i++)
{
if(in[i] == pre[0]) //左右子树的分界线
{
isLeft = false;
}
else if(isLeft) //遍历的是左子树
{
inLeftChildTree.add(in[i]);
}
else //遍历的是右子树
{
inRightChildTree.add(in[i]);
}
}
//获得左右子树的先根遍历
ArrayList preLeftChildTree = new ArrayList<Integer>();
ArrayList preRightChildTree = new ArrayList<Integer>();
for(int i = 1; i < inLeftChildTree.size() + 1; i++)
{
preLeftChildTree.add(pre[i]);
}
for(int i = 1 + inLeftChildTree.size(); i < pre.length; i++)
{
preRightChildTree.add(pre[i]);
}
//将ArrayList转换为int数组
int[] inLeftChildTree0 = intArrayListToIntArray(inLeftChildTree);
int[] inRightChildTree0 = intArrayListToIntArray(inRightChildTree);
int[] preLeftChildTree0 = intArrayListToIntArray(preLeftChildTree);
int[] preRightChildTree0 = intArrayListToIntArray(preRightChildTree);
RootNode.left = reConstructBinaryTree(preLeftChildTree0, inLeftChildTree0);
RootNode.right = reConstructBinaryTree(preRightChildTree0, inRightChildTree0);
return RootNode;
}
//将int型的ArrayList转换为int型数组
private int[] intArrayListToIntArray(ArrayList list) {
int[] temp = new int[list.size()];
for (int i = 0; i < temp.length; i++) {
temp[i] = (int) list.get(i);
}
return temp;
}
}
总结:
学会将大问题分解成重复的小问题,利用递归来解决,这样很多问题都可以迎刃而解了。