难度:中等
给定两个整数数组 inorder
和 postorder
,其中 inorder
是二叉树的中序遍历, postorder
是同一棵树的后序遍历,请你构造并返回这颗 二叉树 。
输入: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
输出:[3,9,20,null,null,15,7]
输入: inorder = [-1], postorder = [-1]
输出:[-1]
因为后序遍历中最后一个元素为根节点,可以根据根节点将中序分割为左右,之后在根据中序左右子树的节点数量等于后续左右子树节点数量分割后续
public class TreeNode
{
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int val = 0, TreeNode left = null, TreeNode right = null)
{
this.val = val;
this.left = left;
this.right = right;
}
}
class Solution
{
public static void Main(string[] args)
{
int[] inorder = { 9, 3, 15, 20, 7 };
int[] postorder = { 9, 15, 7, 20, 3 };
Solution solution = new Solution();
List<int> list = new List<int>();
TreeNode ans = solution.BuildTree(inorder, postorder);
solution.BackTrack(ans, list);
foreach (var a in list)
{
Console.Write(a + " ");
}
}
public TreeNode BuildTree(int[] inorder, int[] postorder)
{
TreeNode root = new(0);
BuildNode(root, inorder, 0, inorder.Length - 1, postorder, 0, postorder.Length - 1);
return root;
}
public void BuildNode(TreeNode node, int[] inorder, int instart, int inend, int[] postorder, int poststart, int postend)
{
node.val = postorder[postend];
int inHead = Array.IndexOf(inorder, node.val);
int inendLeft = inHead - 1;
int postendLeft = poststart + inendLeft - instart;
if (inendLeft >= instart)
{
node.left = new TreeNode(0);
BuildNode(node.left, inorder, instart, inendLeft, postorder, poststart, postendLeft);
}
int instartRight = inHead + 1;
int poststartRight = postendLeft + 1;
if (inend >= instartRight)
{
node.right = new TreeNode(0);
BuildNode(node.right, inorder, instartRight, inend, postorder, poststartRight, postend - 1);
}
}
public void BackTrack(TreeNode root,List<int> list)
{
if (root == null)
{
return;
}
BackTrack(root.left,list);
list.Add(root.val);
BackTrack(root.right,list);
}
}