首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

在 C# 中查找节点的深度

在 C# 中,查找节点的深度可以通过递归遍历树的方式来实现。以下是一个示例代码:

代码语言:csharp
复制
public class TreeNode
{
    public int Val { get; set; }
    public TreeNode Left { get; set; }
    public TreeNode Right { get; set; }
}

public int GetDepth(TreeNode root, int target, int depth)
{
    if (root == null)
    {
        return -1;
    }

    if (root.Val == target)
    {
        return depth;
    }

    int leftDepth = GetDepth(root.Left, target, depth + 1);
    if (leftDepth != -1)
    {
        return leftDepth;
    }

    return GetDepth(root.Right, target, depth + 1);
}

在上述代码中,TreeNode 类表示树的节点,包含一个整数值 Val 和两个子节点 LeftRightGetDepth 方法接收一个根节点 root、一个目标值 target 和当前深度 depth,递归遍历整个树,找到目标节点的深度。

如果找到目标节点,则返回当前深度;如果找不到目标节点,则返回 -1。

在使用上述代码时,可以通过以下方式调用:

代码语言:csharp
复制
TreeNode root = new TreeNode { Val = 1 };
root.Left = new TreeNode { Val = 2 };
root.Right = new TreeNode { Val = 3 };
root.Left.Left = new TreeNode { Val = 4 };
root.Left.Right = new TreeNode { Val = 5 };
root.Right.Left = new TreeNode { Val = 6 };
root.Right.Right = new TreeNode { Val = 7 };

int target = 5;
int depth = GetDepth(root, target, 0);
Console.WriteLine($"The depth of node {target} is {depth}.");

以上代码会输出:

代码语言:txt
复制
The depth of node 5 is 2.

这样,我们就可以通过递归遍历树的方式,找到目标节点的深度。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券