二叉查找树,查找二维数组

在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数

下面是构建二叉查找树,然后搜索,可以直接遍历二维数组查找······
        public class Node
        {
            public int NodeData;
            public Node LeftChild;
            public Node RightChild;
        }


  int[][] array = new int[4][] {new[]{ 1, 5, 9, 13 }, new[] { 2, 6, 10, 14,20,30 }, new[] { 3, 7, 11, 15 }, new[] {4,8, 12, 16,21 } };
            int a = 20;
            Node tree=null;
            Action<int> func = null;
            func = (b) =>
            {
                Node Parent;
                var newNode = new Node() { NodeData =b };
                if (tree == null)
                {
                    tree = newNode;
                }
                else
                {
                    Node Current = tree;
                    while (true)
                    {
                        Parent = Current;
                        if (newNode.NodeData < Current.NodeData)
                        {
                            Current = Current.LeftChild;
                            if (Current == null)
                            {
                                Parent.LeftChild = newNode;
                                break;
                            }
                        }
                        else
                        {
                            Current = Current.RightChild;
                            if (Current == null)
                            {
                                Parent.RightChild = newNode;
                                //插入叶子后跳出循环
                                break;
                            }
                        }
                    }
                }
            };
  
            for (int i = 0; i < array.Length; i++)
            {
                for (int j = 0; j < array[i].Length; j++)
                {
                    func(array[i][j]);
                }
            }
            Func<int,bool> check = null;
            check = (t) =>
            {
                var current = tree;
                while (true)
                {
                    if (t < current.NodeData)
                    {
                        if (current.LeftChild == null) break;
                        current = current.LeftChild;
                    }
                    else if (t > current.NodeData)
                    {
                        if (current.RightChild == null) break;
                        current = current.RightChild;
                    }
                    else
                    {
                        return true;
                    }
                }
                return false;
            };
            Console.WriteLine(check(a));

 

 

    原文作者:季末的寂寞
    原文地址: https://www.cnblogs.com/onegarden/p/6801364.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞