Пример #1
0
        private void Bottom_View_Of_BinaryTree_Click(object sender, EventArgs e)
        {
            BTNodeHD root = new BTNodeHD(1);

            root.left             = new BTNodeHD(2);
            root.right            = new BTNodeHD(3);
            root.left.right       = new BTNodeHD(4);
            root.right.left       = new BTNodeHD(5);
            root.right.right      = new BTNodeHD(6);
            root.right.left.left  = new BTNodeHD(7);
            root.right.left.right = new BTNodeHD(8);

            var map = BottomViewOfBinaryTree(root);

            // Print Bottom View
            Console.WriteLine("Bottom View of Binary Tree: ");
            foreach (var pair in map)
            {
                Console.Write(pair.Value[pair.Value.Count - 1] + ", ");
            }
            Console.WriteLine("");
            // Print Top View
            Console.WriteLine("Top View of Binary Tree: ");
            foreach (var pair in map)
            {
                Console.Write(pair.Value[0] + ", ");
            }
        }
Пример #2
0
        private Dictionary <int, List <int> > BottomViewOfBinaryTree(BTNodeHD node)
        {
            if (node == null)
            {
                return(null);
            }

            Queue <BTNodeHD> queue = new Queue <BTNodeHD>();

            queue.Enqueue(node);

            Dictionary <int, List <int> > map = new Dictionary <int, List <int> >();

            while (queue.Count > 0)
            {
                var curr     = queue.Dequeue();
                var currDist = curr.distane;
                if (!map.ContainsKey(currDist))
                {
                    map.Add(currDist, new List <int>());
                }
                map[currDist].Add(curr.data);

                if (curr.left != null)
                {
                    curr.left.distane = curr.distane - 1;
                    queue.Enqueue(curr.left);
                }

                if (curr.right != null)
                {
                    curr.right.distane = curr.distane + 1;
                    queue.Enqueue(curr.right);
                }
            }
            return(map);
        }