多叉树查找


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;
    }
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM