Пример #1
0
        /// Sum of leaf nodes helper to find the minimum level
        static int FindMinLevel(Node root)
        {
            Queue <Node> queue = new Queue <Node>();

            root.level = 0;
            queue.Enqueue(root);

            while (queue.Count > 0)
            {
                Node node = queue.Dequeue();

                if (node.left == null && node.right == null)
                {
                    return(node.level);
                }

                if (node.left != null)
                {
                    node.left.level = node.level + 1;
                    queue.Enqueue(node.left);
                }
                if (node.right != null)
                {
                    node.right.level = node.level + 1;
                    queue.Enqueue(node.right);
                }
            }

            return(0);
        }
Пример #2
0
 /// Print out all root to leaf path per line of a binary tree
 /// https://www.geeksforgeeks.org/given-a-binary-tree-print-out-all-of-its-root-to-leaf-paths-one-per-line/
 static void PrintRootToLeafPath(Node root)
 {
     PrintRootToLeafHelper(root, new List <Node>()
     {
         root
     });
 }
Пример #3
0
        /// Given 2 nodes, find the distance between them
        ///  https://www.geeksforgeeks.org/find-distance-between-two-nodes-of-a-binary-tree/
        static int FindDistanceBetweenTwoNodes(Node root, int firstNode, int secondNode)
        {
            Queue <Node> firstNodePath  = FindPathNonBST(root, firstNode, new Queue <Node>());
            Queue <Node> secondNodePath = FindPathNonBST(root, secondNode, new Queue <Node>());

            while (firstNodePath.Count > 0 && secondNodePath.Count > 0)
            {
                if (firstNodePath.Peek().data != secondNodePath.Peek().data)
                {
                    // lca hit
                    break;
                }
                firstNodePath.Dequeue();
                secondNodePath.Dequeue();
            }

            int distance = 0;

            while (firstNodePath.Count > 0)
            {
                distance++;
                firstNodePath.Dequeue();
            }
            while (secondNodePath.Count > 0)
            {
                distance++;
                secondNodePath.Dequeue();
            }

            return(distance);
        }
Пример #4
0
        static void PrintRootToLeafHelper(Node node, List <Node> path)
        {
            if (node.left == null && node.right == null)
            {
                // print path
                foreach (Node n in path)
                {
                    Console.Write(n.data + " ");
                }
                Console.WriteLine();
            }
            else
            {
                if (node.left != null)
                {
                    path.Add(node.left);
                    PrintRootToLeafHelper(node.left, path);
                    path.Remove(node.left);
                }

                if (node.right != null)
                {
                    path.Add(node.right);
                    PrintRootToLeafHelper(node.right, path);
                    path.Remove(node.right);
                }
            }
        }
Пример #5
0
        /// <summary>
        /// Level order traversal. Also called a breadth first serach
        /// </summary>
        /// <param name="root"></param>
        static void LevelOrderTraversal(Node root)
        {
            if (root == null)
            {
                return;
            }

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

            queue.Enqueue(root);

            while (queue.Count != 0)
            {
                Node tempNode = queue.Dequeue();
                Console.WriteLine(tempNode.data);

                if (tempNode.left != null)
                {
                    queue.Enqueue(tempNode.left);
                }

                if (tempNode.right != null)
                {
                    queue.Enqueue(tempNode.right);
                }
            }
        }
Пример #6
0
        public void Main_Tree()
        {
            Node tree = Tree.CreateTree();

            //bool result = checkBST(tree);

            //Node lowestCommonAncentor = lca(tree, 10, 14);
            //Console.WriteLine(lowestCommonAncentor.data);

            MirrorImageATree(tree);

            //LevelOrder(tree);

            //Node root = InsertIntoBST(tree, 8);

            //var sum = SumOfLeafNodeAtMinLevel(tree);
            //Console.WriteLine(sum);

            //var height = HeightOfBinaryTree(tree);
            //Console.WriteLine(height);

            //PrintRootToLeafPath(tree);

            //BinaryTreeToDoublyList(tree);
        }
Пример #7
0
        /// Check if binary tree is skewed
        /// Skewed binary tree: If each node has only one child or none
        static bool IsBinaryTreeSkewed(Node root)
        {
            Queue <Node> queue = new Queue <Node>();

            queue.Enqueue(root);

            while (queue.Count > 0)
            {
                Node node = queue.Dequeue();

                if (node.left != null && node.right != null)
                {
                    return(false);
                }

                if (node.left != null)
                {
                    queue.Enqueue(node.left);
                }

                if (node.right != null)
                {
                    queue.Enqueue(node.right);
                }
            }

            return(true);
        }
Пример #8
0
        /// Print left view of a binary tree
        /// https://www.geeksforgeeks.org/print-left-view-binary-tree/
        static void PrintLeftView(Node root)
        {
            Queue <Node> queue = new Queue <Node>();

            int previousLevel = -1;

            root.level = 0;
            queue.Enqueue(root);

            while (queue.Count > 0)
            {
                Node node = queue.Dequeue();

                if (node.level > previousLevel)
                {
                    Console.Write(node.data + " ");
                    previousLevel = node.level;
                }

                if (node.left != null)
                {
                    node.left.level = node.level + 1;
                    queue.Enqueue(node.left);
                }
                if (node.right != null)
                {
                    node.right.level = node.level + 1;
                    queue.Enqueue(node.right);
                }
            }
        }
Пример #9
0
        static bool checkBSTHelper(Node node, int min, int max)
        {
            // base case
            if (node == null) // ?
            {
                return(true);
            }

            // recurse small pieces
            bool result = true;

            if (node.left != null)
            {
                if (node.left.data > node.data || node.left.data > max || node.left.data < min)
                {
                    return(false);
                }
            }
            if (node.right != null)
            {
                if (node.right.data < node.data || node.right.data < min || node.right.data > max)
                {
                    return(false);
                }
            }

            result = checkBSTHelper(node.left, min, node.data);
            result = result && checkBSTHelper(node.right, node.data, max);
            return(result);
        }
Пример #10
0
 /// Insert node into BST helper
 static void InsertHelper(ref Node root, int data)
 {
     if (data < root.data)
     {
         if (root.left == null)
         {
             Node node = new Node()
             {
                 data = data
             };
             root.left = node;
         }
         else
         {
             InsertIntoBST(root.left, data);
         }
     }
     else
     {
         if (root.right == null)
         {
             Node node = new Node()
             {
                 data = data
             };
             root.right = node;
         }
         else
         {
             InsertIntoBST(root.right, data);
         }
     }
 }
Пример #11
0
        /// Finds the maximum path sum across the tree
        static int MaxPathSum(Node root)
        {
            int[] max = new int[1];
            max[0] = int.MinValue;
            MaxPathSumHelper(root, max);

            return(max[0]);
        }
Пример #12
0
        static void PostOrder(Node node)
        {
            if (node == null)
            {
                return;
            }

            PostOrder(node.left);
            PostOrder(node.right);
            Console.WriteLine(node.data);
        }
Пример #13
0
        // Mirror image sub function to swap child nodes
        static Node SwapChildNodes(Node node)
        {
            if (node != null)
            {
                Node temp = node.left;
                node.left  = node.right;
                node.right = temp;
            }

            return(node);
        }
Пример #14
0
 /// Binary tree height/depth helper
 static int FindHeightHelper(Node node)
 {
     // base case
     if (node == null)
     {
         return(0);
     }
     else
     {
         // Find max of left or right height
         return(Math.Max(FindHeightHelper(node.left) + 1, FindHeightHelper(node.right) + 1));
     }
 }
Пример #15
0
        public void Main_Tree()
        {
            Node tree = Tree.CreateTree();

            //LevelOrderSpiralTraversal(tree);

            //int maxPathSum = MaxPathSum(tree);

            // PrintLeftView(tree);

            //bool isTreeSkewed = IsBinaryTreeSkewed(tree);
            //Console.WriteLine(isTreeSkewed);
        }
Пример #16
0
        /// Convert binary tree to a doubly linked list
        /// https://www.geeksforgeeks.org/in-place-convert-a-given-binary-tree-to-doubly-linked-list/
        static Node BinaryTreeToDoublyList(Node node)
        {
            if (node == null)
            {
                return(node);
            }

            node = BinaryTreeToDoublyListHelper(node);

            while (node.left != null)
            {
                node = node.left;
            }

            return(node);
        }
Пример #17
0
        static Queue <Node> FindPathNonBST(Node root, int key, Queue <Node> path)
        {
            path.Enqueue(root);

            if (root.data == key)
            {
                return(path);
            }
            else
            {
                FindPathNonBST(root.left, key, path);
                FindPathNonBST(root.right, key, path);
            }

            return(null);
        }
Пример #18
0
        static int MaxPathSumHelper(Node root, int[] max)
        {
            if (root == null)
            {
                return(0);
            }

            int left  = MaxPathSumHelper(root.left, max);
            int right = MaxPathSumHelper(root.right, max);

            int current = Math.Max(root.data, Math.Max(root.data + left, root.data + right));

            max[0] = Math.Max(max[0], Math.Max(current, left + root.data + right));

            return(current);
        }
Пример #19
0
        static bool checkBSTHelper2(Node node, int min, int max)
        {
            // base case
            if (node == null)
            {
                return(true);
            }

            if (min < node.data && max > node.data)
            {
                return(checkBSTHelper2(node.left, min, node.data) && checkBSTHelper2(node.right, node.data, max));
            }
            else
            {
                return(false);
            }
        }
Пример #20
0
        static void LevelOrderSpiralTraversal(Node root)
        {
            if (root == null)
            {
                return;
            }

            Stack <Node> s1 = new Stack <Node>();
            Stack <Node> s2 = new Stack <Node>();

            s1.Push(root);

            while (s1.Count > 0 || s2.Count > 0)
            {
                while (s1.Count > 0)
                {
                    Node node = s1.Pop();
                    Console.WriteLine(node.data + " ");

                    if (node.right != null)
                    {
                        s2.Push(node.right);
                    }
                    if (node.left != null)
                    {
                        s2.Push(node.left);
                    }
                }

                while (s2.Count > 0)
                {
                    Node node = s2.Pop();
                    Console.WriteLine(node.data + " ");

                    if (node.left != null)
                    {
                        s1.Push(node.left);
                    }
                    if (node.right != null)
                    {
                        s1.Push(node.right);
                    }
                }
            }
        }
Пример #21
0
        static Node BinaryTreeToDoublyListHelper(Node node)
        {
            // base case
            if (node == null)
            {
                return(node);
            }

            if (node.left != null)
            {
                // convert left sub tree
                Node left = BinaryTreeToDoublyListHelper(node.left);

                // find in order predecessor
                while (left.right != null)
                {
                    left = left.right;
                }

                // point predessor's next to root and root's previous to predessor
                left.right = node;
                node.left  = left;
            }

            if (node.right != null)
            {
                // convert right sub tree
                Node right = BinaryTreeToDoublyListHelper(node.right);

                // find inorder successor
                while (right.left != null)
                {
                    right = right.left;
                }

                // point predessor's previous to root and root's next to predessor
                right.left = node;
                node.right = right;
            }

            return(node);
        }
Пример #22
0
        /// LCA helper, finds path to a node and returns in a queue form
        static Queue <Node> FindPath(Node root, int key, Queue <Node> path)
        {
            path.Enqueue(root);

            if (root.data == key)
            {
                return(path);
            }
            else
            {
                if (key < root.data)
                {
                    return(FindPath(root.left, key, path));
                }
                else if (key > root.data)
                {
                    return(FindPath(root.right, key, path));
                }
            }
            return(null); // when will this hit ?
        }
Пример #23
0
        /// Prints the tree nodes in a level order traversal
        static void LevelOrder(Node root)
        {
            Queue <Node> queue = new Queue <Node>();

            queue.Enqueue(root);

            while (queue.Count > 0)
            {
                Node node = queue.Dequeue();
                Console.WriteLine(node.data);

                if (node.left != null)
                {
                    queue.Enqueue(node.left);
                }
                if (node.right != null)
                {
                    queue.Enqueue(node.right);
                }
            }
        }
Пример #24
0
        /// Find sum of all leaf nodes at the level nearest to root
        /// https://www.geeksforgeeks.org/sum-leaf-nodes-minimum-level/
        static int SumOfLeafNodeAtMinLevel(Node root)
        {
            int          minLevel = FindMinLevel(root);
            Queue <Node> queue    = new Queue <Node>();

            root.level = 0;
            queue.Enqueue(root);

            int sum = 0;

            while (queue.Count > 0)
            {
                Node node = queue.Dequeue();

                if (node.level < minLevel)
                {
                    if (node.left != null)
                    {
                        node.left.level = node.level + 1;
                        queue.Enqueue(node.left);
                    }
                    if (node.right != null)
                    {
                        node.right.level = node.level + 1;
                        queue.Enqueue(node.right);
                    }
                }
                else if (node.level == minLevel)
                {
                    if (node.left == null && node.right == null)
                    {
                        sum += node.data;
                    }
                }
            }

            return(sum);
        }
Пример #25
0
        /// Convert tree to a mirror image of itself
        static Node MirrorImageATree(Node root)
        {
            Queue <Node> queue = new Queue <Node>();

            queue.Enqueue(root);

            while (queue.Count > 0)
            {
                Node node = queue.Dequeue();
                SwapChildNodes(node);

                if (node.left != null)
                {
                    queue.Enqueue(node.left);
                }
                if (node.right != null)
                {
                    queue.Enqueue(node.right);
                }
            }

            return(root);
        }
Пример #26
0
        /// Find the lowest common ancestor of two nodes in a tree
        static Node lca(Node root, int v1, int v2)
        {
            Queue <Node> v1Path = new Queue <Node>();
            Queue <Node> v2Path = new Queue <Node>();

            v1Path = FindPath(root, v1, v1Path);
            v2Path = FindPath(root, v2, v2Path);

            // loop through queue and stop when nodes are uncommon,
            // return last common node
            Node previous = new Node();

            while (v1Path.Count != 0 && v2Path.Count() != 0)
            {
                if (v1Path.Peek().data != v2Path.Peek().data)
                {
                    return(previous);
                }
                previous = v1Path.Dequeue();
                v2Path.Dequeue();
            }

            return(previous);
        }
Пример #27
0
 /// Insert given value into a BST and return pointer to the root
 static Node InsertIntoBST(Node root, int data)
 {
     InsertHelper(ref root, data);
     return(root);
 }
Пример #28
0
 /// Finds the height/depth of a binary tree
 static int HeightOfBinaryTree(Node root)
 {
     return(FindHeightHelper(root));
 }
Пример #29
0
 /// checks if a tree is BST
 static bool checkBST(Node root)
 {
     return(checkBSTHelper2(root, int.MinValue, int.MaxValue));
 }