继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

多叉树查找

Qyou
关注TA
已关注
手记 255
粉丝 52
获赞 361
public class NodeTree{    public string Value { get; set; }    public List<NodeTree> ChildTree { get; set; }}class Program{    static void Main(string[] args) {        var tree = new NodeTree() {            Value = "1",            ChildTree = new List<NodeTree>() {                new NodeTree(){ Value="1-1",                    ChildTree =new List<NodeTree>(){                        new NodeTree() { Value="1-1-1"},                        new NodeTree() { Value="1-1-2"}                    }                },                new NodeTree(){ Value="1-2",                    ChildTree =new List<NodeTree>(){                        new NodeTree() { Value="1-2-1"},                        new NodeTree() { Value="1-2-2",                            ChildTree=new List<NodeTree>(){                                new NodeTree() { Value="1-2-2-1"}                            }                        }                    }                },                new NodeTree(){ Value="1-3"}            }        };        var node = SearchNode(tree, "1-3");        Console.WriteLine(node.Value);        Console.WriteLine("===================");        node = SearchNode2(tree, "1-2-1");        Console.WriteLine(node.Value);    }    //深度优先,递归    static NodeTree SearchNode(NodeTree tree, string valueToFind) {        if (tree.Value == valueToFind) {            return tree;        }        else {            if (tree.ChildTree != null) {                foreach (var item in tree.ChildTree) {                    var temp = SearchNode(item, valueToFind);                    if (temp != null) return temp;                }            }        }        return null;    }    //堆栈    static NodeTree SearchNode2(NodeTree rootNode, string valueToFind) {        var stack = new Stack<NodeTree>(new[] { rootNode });        while (stack.Any()) {            var n = stack.Pop();            if (n.Value == valueToFind) return n;            if (n.ChildTree != null)                foreach (var child in n.ChildTree) stack.Push(child);        }        return null;    }}
打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP