已知前序和中序
public class TreeNode
{
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) { val = x; }
}
public TreeNode BuildTree1(int[] preorder, int[] inorder)
{
if (preorder == null || inorder == null) return null;
return ReBuildTree1(preorder,0,preorder.Length-1,inorder,0, inorder.Length-1);
}
TreeNode ReBuildTree1(int[] preTree,int startPre,int endPre,int[] inTree,int startIn,int endIn)
{
if (startPre > endPre || startIn > endIn) return null;
//前序遍历数组的第一个元素就是子树的根节点
TreeNode root = new TreeNode(preTree[startPre]);
//在中序中找到和根节点相同的节点
for (int i = startIn; i <= endIn; i++)
{
if(inTree[i] == preTree[startPre])
{
//其中(i-startIn)为中序排序中左子树节点的个数
int leftLength = i - startIn;//左子树的长度
int preStartRight = startPre + leftLength + 1;//右子树开始的
int preStartLeft = startPre + 1;//左子树开始
//左子树
root.left = ReBuildTree1(preTree, preStartLeft, startPre + leftLength, inTree, startIn, i - 1);
root.right = ReBuildTree1(preTree, preStartRight, endPre, inTree, i+1, endIn);
}
}
return root;
}
已知后序和中序
public TreeNode BuildTree(int[] inorder, int[] postorder)
{
if (inorder == null || postorder == null) return null;
return ReBuildTree(inorder, 0, inorder.Length - 1, postorder, 0, postorder.Length - 1);
}
TreeNode ReBuildTree(int[] inorder, int startIn, int endIn, int[] postorder, int startPost, int endPost)
{
if (startIn > endIn || startPost < 0) return null;
//后序序遍历数组的最后一个元素就是子树的根节点
TreeNode root = new TreeNode(postorder[endPost]);
//在中序中找到和根节点相同的节点
for (int i = startIn; i <= endIn; i++)
{
if (inorder[i] == postorder[endPost])
{
//i-startIn为左子树的长度
int postStartLeft = startPost+i-startIn;
int postStartRight = startPost + i - startIn-1;
//左子树
root.left = ReBuildTree(inorder, startIn , i-1, postorder, startPost, postStartRight);
root.right = ReBuildTree(inorder, i + 1,endIn , postorder, postStartLeft, endPost-1);
}
}
return root;
}