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;
        }
    }
    
    
  • 相关阅读:
    LeetCode120 Triangle
    LeetCode119 Pascal's Triangle II
    LeetCode118 Pascal's Triangle
    LeetCode115 Distinct Subsequences
    LeetCode114 Flatten Binary Tree to Linked List
    LeetCode113 Path Sum II
    LeetCode112 Path Sum
    LeetCode111 Minimum Depth of Binary Tree
    Windows下搭建PHP开发环境-WEB服务器
    如何发布可用于azure的镜像文件
  • 原文地址:https://www.cnblogs.com/savorboard/p/6582399.html
Copyright © 2011-2022 走看看