题解 | #重建二叉树#
重建二叉树
https://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6
using System;
using System.Collections.Generic;
/*
public class TreeNode
{
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode (int x)
{
val = x;
}
}
*/
class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pre int整型一维数组
* @param tin int整型一维数组
* @return TreeNode类
*/
public TreeNode reConstructBinaryTree (List<int> pre, List<int> vin) {
// write code here
int n = pre.Count;
int m = vin.Count;
if (m == 0 || n == 0)
return null;
TreeNode root = new TreeNode(pre[0]);
for (int i = 0; i < vin.Count; i++) {
if (pre[0] == vin[i]) {
List<int> leftpre = new List<int>(pre.GetRange(1, i));
List<int> leftvin = new List<int>(vin.GetRange(0, i));
root.left = reConstructBinaryTree(leftpre, leftvin);
List<int> rightpre = new List<int>(pre.GetRange(i + 1, vin.Count - (i + 1)));
List<int> rightvin = new List<int>(vin.GetRange(i + 1, vin.Count - (i + 1)));
root.right = reConstructBinaryTree(rightpre, rightvin);
}
}
return root;
}
}

查看10道真题和解析