C# 使用递归查询树的所有父节点

背景:公司项目要实现兼容 MS SQL、Oracle、PgSQL、DM 等多种数据库,由于各种数据库对递归实现方式不尽相同,如果每种数据库都写一种 SQL 语句来实现,未免太多,且需求是不定的,哪天又加一种数据库,会很大的增加代码的维护成本。因此为了更好的同时兼容多种数据库,我们可以用代码代替 SQL 语句来实现递归查询。

实现:

List<string> parentOrg = new List<string>();

/// <summary>
/// 递归查询父级ID
/// </summary>
/// <param name="id"></param>
/// <param name="list"></param>
/// <returns></returns>
private string GetParents(string id, List<dynamic> list)
{
    parentOrg.Add(id);
    List<dynamic> result = list.Where(x => x.ID == id).ToList();
    if (result.Count > 0 && result[0].ParentID != null && result[0].ParentID.ToString() != "")
        return GetParents(result[0].ParentID, list);
    else
        return id;
}

public static class Main(string[] args)
{
    string id = '3'; //当前节点id
    List<dynamic> listAll; //result是符合包含当前节点在内的所有节点的列表
    GetParents(id, listAll);
    List<dynamic> result = parentOrg; //得到的result就是当前节点+当前节点的所有父级
}

 

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个C#的示例代码,用于计算霍夫曼的WPL。 ```csharp using System; using System.Collections.Generic; namespace HuffmanTreeWPL { class Node { public int Weight; public Node LeftChild; public Node RightChild; public Node(int weight) { this.Weight = weight; this.LeftChild = null; this.RightChild = null; } } class Program { static void Main(string[] args) { int[] weights = { 5, 3, 2, 1, 1 }; Node root = BuildHuffmanTree(weights); int wpl = CalculateWPL(root, 0); Console.WriteLine("The WPL of the Huffman tree is: " + wpl); } static Node BuildHuffmanTree(int[] weights) { List<Node> nodes = new List<Node>(); foreach (int weight in weights) { nodes.Add(new Node(weight)); } while (nodes.Count > 1) { nodes.Sort((a, b) => a.Weight - b.Weight); Node leftChild = nodes[0]; Node rightChild = nodes[1]; Node parent = new Node(leftChild.Weight + rightChild.Weight); parent.LeftChild = leftChild; parent.RightChild = rightChild; nodes.Remove(leftChild); nodes.Remove(rightChild); nodes.Add(parent); } return nodes[0]; } static int CalculateWPL(Node root, int depth) { if (root.LeftChild == null && root.RightChild == null) { return root.Weight * depth; } int leftWPL = CalculateWPL(root.LeftChild, depth + 1); int rightWPL = CalculateWPL(root.RightChild, depth + 1); return leftWPL + rightWPL; } } } ``` 在这个示例代码中,我们首先定义了一个`Node`类表示霍夫曼的节点。每个节点包含一个权重值和两个子节点(左子节点和右子节点)。接下来,我们编写了一个`BuildHuffmanTree`方法,用于构建霍夫曼。该方法接受一个整数数组作为输入,表示每个字符出现的频率。我们使用一个列表来存储每个节点,并逐个将其添加到列表中。然后,我们按照权重对节点进行排序,选择两个权重最小的节点作为父节点,并将它们组成一个新的节点。最后,我们将新节点添加到节点列表中,直到只剩下一个节点,即霍夫曼的根节点。 接下来,我们编写了一个`CalculateWPL`方法,用于计算霍夫曼的WPL。该方法接受一个节点和一个深度值作为输入,表示当前节点的深度。如果当前节点是叶子节点,则返回该节点的权重值乘以深度值。否则,我们递归地计算左子和右子的WPL,并将它们相加。 最后,在`Main`方法中,我们定义了一个整数数组表示字符的频率,并使用`BuildHuffmanTree`方法构建了霍夫曼。然后,我们调用`CalculateWPL`方法计算霍夫曼的WPL,并将结果输出到控制台。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值