Ejemplo n.º 1
0
        static BST ReconstructBSTFromRange(int lowerBound, int upperBound,
                                           List <int> preOrderTraversalValues,
                                           TreeInfo currentSubtreeInfo)
        {
            if (currentSubtreeInfo.rootIdx == preOrderTraversalValues.Count)
            {
                return(null);
            }

            int rootValue = preOrderTraversalValues[currentSubtreeInfo.rootIdx];

            if (rootValue < lowerBound || rootValue >= upperBound)
            {
                return(null);
            }

            currentSubtreeInfo.rootIdx += 1;

            BST leftSubtree = ReconstructBSTFromRange(lowerBound, rootValue,
                                                      preOrderTraversalValues,
                                                      currentSubtreeInfo);

            BST rightSubtree = ReconstructBSTFromRange(rootValue, upperBound,
                                                       preOrderTraversalValues,
                                                       currentSubtreeInfo);


            BST bst = new BST(rootValue);

            bst.left  = leftSubtree;
            bst.right = rightSubtree;

            return(bst);
        }
Ejemplo n.º 2
0
        static BST ReconstructBst(List <int> preOrderTraversalValues)
        {
            TreeInfo treeInfo = new TreeInfo(0);

            return(ReconstructBSTFromRange(Int32.MinValue, Int32.MaxValue, preOrderTraversalValues, treeInfo));
        }