using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
int[] preorder = { 1, 2, 4, 7, 3, 5, 6, 8 };
int[] inorder = { 4, 7, 2, 1, 5, 3, 8, 6 };
Solution solution = new Solution();
TreeNode treeNode =solution.reConstructBinatryTree(preorder, inorder);
Console.WriteLine(treeNode);
}
}
public class TreeNode
{
public int data;
public TreeNode left;
public TreeNode right;
public TreeNode(int n)
{
data = n;
left = null;
right = null;
}
}
public class Solution
{
public TreeNode reConstructBinatryTree(int[] preorder ,int[] inorder)
{
if(preorder == null || inorder == null)
{
return null;
}
TreeNode root = rebuileBinaryTree(preorder, 0, preorder.Length - 1, inorder, 0, inorder.Length - 1);
return root;
}
private TreeNode rebuileBinaryTree(int[] preorder,int startPreorder,int endPreorder,int[] inorder,int startInorder,int endInorder)
{
if(startPreorder > endPreorder || startInorder > endInorder)
{
return null;
}
TreeNode root = new TreeNode(preorder[startPreorder]);
for (int i = startInorder; i <= endInorder; i++)
{
if(preorder[startPreorder] == inorder[i])
{
//(i - startInorder)为中序遍历中左子树节点的个数
root.left = rebuileBinaryTree(preorder, startPreorder + 1, startPreorder + (i - startInorder), inorder, startInorder, i - 1);
root.right = rebuileBinaryTree(preorder, (i - startInorder) + startPreorder + 1, endPreorder, inorder, i + 1, endInorder);
}
}
return root;
}
}
}
解决问题的精髓在于:每次递归时,是将一颗完整的二叉树分成左子树、根、右子树,再对每个子树继续分,大问题一步步化解为小问题并解决。