Exemple #1
0
            private void DFS(TreeNode node, BinaryHeap <int> minHeap)
            {
                if (node == null)
                {
                    return;
                }

                // SS: pre-order
                minHeap.Push(node.val);

                TestContext.Progress.WriteLine(node.val);

                DFS(node.left, minHeap);
                DFS(node.right, minHeap);
            }
Exemple #2
0
            public int KthSmallest1(TreeNode root, int k)
            {
                var minHeap = BinaryHeap <int> .CreateHeap((p1, p2) => p1 > p2);

                // SS: O(n * log n)
                // n vertices, each pushed into min heap at log n each
                DFS(root, minHeap);

                // SS: O(k log n)
                var value = -1;
                var n     = 0;

                while (n < k)
                {
                    value = minHeap.Pop();
                    n++;
                }

                // SS: total O(n log n)
                // SS: O(log n) stack space and O(n) minheap
                return(value);
            }