zoukankan      html  css  js  c++  java
  • 多叉树查找

    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;
        }
    }
    
    
  • 相关阅读:
    差分约束
    POJ 2449 Remmarguts' Date[k短路]
    K短路
    hdu4034 Graph(floyd)
    hdu2089不要62(数位dp)
    POJ3468 A Simple Problem with Integers ( 线段树)
    POJ3255:Roadblocks(次短路 SPFA+A星)
    usaco2.1Ordered Fractions( 枚举, 数学)
    hdu1565方格取数(1) (状态压缩dp)
    poj3259 Wormholes(spfa)
  • 原文地址:https://www.cnblogs.com/savorboard/p/6582399.html
Copyright © 2011-2022 走看看