【发布时间】:2018-05-13 12:46:02
【问题描述】:
以下程序返回树是否平衡。如果从根到任何叶子的路径长度相同,则称一棵树是平衡的。
using System;
namespace BalancedTree
{
public class MainClass
{
static bool isBalanced(int[][] sons)
{
return isBalanced(sons, 0);
}
static bool isBalanced(int[][] sons, int startNode)
{
int[] children = sons[startNode];
int minHeight = int.MaxValue;
int maxHeight = int.MinValue;
bool allChildBalanced = true;
if(children.Length == 0)
return true;
else
{
foreach (int node in children)
{
int h = height(sons, node);
if(h > maxHeight)
maxHeight = h;
if(h < minHeight)
minHeight = h;
}
}
foreach (int node in children)
{
allChildBalanced = allChildBalanced && isBalanced(sons, node);
if(!allChildBalanced)
return false;
}
return Math.Abs(maxHeight - minHeight) < 2 && allChildBalanced;
}
static int height(int[][] sons, int startNode)
{
int maxHeight = 0;
foreach (int child in sons[startNode])
{
int thisHeight = height(sons, child);
if(thisHeight > maxHeight)
maxHeight = thisHeight;
}
return 1 + maxHeight;
}
public static void Main (string[] args)
{
int[][] sons = new int[6][];
sons[0] = new int[] { 1, 2, 4 };
sons[1] = new int[] { };
sons[2] = new int[] { 3, 5};
sons[3] = new int[] { };
sons[4] = new int[] { };
sons[5] = new int[] { };
Console.WriteLine (isBalanced(sons));
}
}
}
我的问题是我的代码效率很低,因为递归调用函数
static int height(int[][] sons, int startNode)
使时间复杂度成指数级。 我知道这可以在二叉树的情况下进行优化,但我正在寻找一种方法来优化我的程序,以防上面描述的一般树。 例如,一种想法是从当前节点而不是 startNode 调用函数“height”。 我唯一的限制是时间复杂度必须是线性的,但我可以使用额外的内存。
【问题讨论】:
-
我并没有真正看到树,我看到的只是一个锯齿状的二维数组。这不是我熟悉的树结构。我希望有一个类似
public interface INode<T>{ T Value { get;set; } INode<T> Parent { get;set; } IEnumerable<INode<T>> ChildNodes { get; } void AddChild(INode<T> childNode); }或类似合同的结构。 -
我使用了一个邻接列表
int[][] sons,其中节点 0 是根,我们定义了从根到叶子的边。这种表示是树邻接表。
标签: c# tree graph-theory balance