我有这个代码来找到二叉树的直径。 二叉树的直径:树的直径(有时称为宽度)是树中两棵树叶之间最长路径上的节点数。递归 - 二叉树
我想了解下面的代码和一般的递归。我试图用这个简单的树干运行。我明白什么时候root的高度会变成1(Max(0,0)+1),然后返回Math.Max(0 + 0 + 1,Max(0,0))。我的理解是,它将根据此返回值将ldiameter设置为1,而root = 10。这是正确的吗?此时lh变为1.它如何变为1?另外,如果你可以帮助我干一步一步地运行这个简单的树,这将是非常有用的。
10
/ \
20 30
public int FindDiameter_util(Node root, ref int height)
{
/* lh --> Height of left subtree
rh --> Height of right subtree */
int lh = 0, rh = 0;
/* ldiameter --> diameter of left subtree
rdiameter --> Diameter of right subtree */
int ldiameter = 0, rdiameter = 0;
if (root == null)
{
height = 0;
return 0; /* diameter is also 0 */
}
/* Get the heights of left and right subtrees in lh and rh
And store the returned values in ldiameter and ldiameter */
ldiameter = FindDiameter_util(root.left, ref lh);
rdiameter = FindDiameter_util(root.right, ref rh);
/* Height of current node is max of heights of left and
right subtrees plus 1*/
height = Math.Max(lh, rh) + 1;
return Math.Max(lh + rh + 1, Math.Max(ldiameter, rdiameter));
}
我给你的建议:第一,破除一切'ref's的。将其转换为一个方法,该方法返回一个由名称为Height和Diameter的两个整数组成的不可变结构。其次,你必须有解释变量名称的意见,这意味着它们被命名得很糟糕。他们应该是'leftDiameter','leftHeight',等等。第三,编写算法,以便每个变量只写入一次。当你这样做时,代码将更容易理解。 –
你是对的,用裁判的是什么让我迷惑。感谢您的其他建议。 – Kar