我被安排了一个我试图解决的问题。这个问题需要在一棵二叉树的一个方向上找到最大的高度。例如,如果分支继续向左,则高度继续增加,但如果分支继续向右,则高度将重置为1。
我在C#中提出了以下几点,我甚至不确定它是否正确。
有人知道最优解吗?
class MaxHeightInOneDirection
{
public void Run()
{
Tree a = new Tree();
a.x= 20;
Tree b = new Tree();
b.x = 21;
Tree c = new Tree();
c.x = 12;
c.l = b;
c.r = a;
Tree d = new Tree();
d.x = 10;
d.l = c;
Tree e = new Tree();
e.x = 3;
Tree f = new Tree();
f.x = 5;
f.l = e;
f.r = d;
int maxHeight = GetHeight(f)[2];
}
public int[] GetHeight(Tree root)
{
if (root == null)
return new int[]{-1,-1, 0};
int[] leftResult = GetHeight(root.l);
int[] rightResult = GetHeight(root.r);
// Increase left on current left
leftResult[0]++;
// Set right result on current left to 0
leftResult[1] = 0;
// Set left result on current right to 0
rightResult[0] = 0;
// Increase right on current right
rightResult[1]++;
int leftMaxSoFar = leftResult[2];
int rightMaxSoFar = rightResult[2];
int maxValueSoFar = Math.Max(leftMaxSoFar, leftResult[0]);
maxValueSoFar = Math.Max(maxValueSoFar, rightResult[1]);
maxValueSoFar = Math.Max(maxValueSoFar, rightMaxSoFar);
return new int[] { leftResult[0], rightResult[1], maxValueSoFar };
}
}
最佳答案
若要查找树的高度,只需使用此算法:-here
做点什么
int MaxDepth(Tree node)
{
if (node==NULL)
return 0;
else
{
int lDepth = maxDepth(node->left);
int rDepth = maxDepth(node->right);
/* use the larger one */
if (lDepth > rDepth)
return(lDepth+1);
else return(rDepth+1);
}
}