예제 #1
0
# Definition for a binary tree node.
# in order tree traverse can get a sorted list for BST
# The minimum value difference between two neighbors in a sorted list is the answer.

from utils import stringToTreeNode, prettyPrintTree


class Solution:
    def getMinimumDifference(self, root):
        L = []

        def dfs(node):
            if node.left: dfs(node.left)
            L.append(node.val)
            if node.right: dfs(node.right)

        dfs(root)
        return min(b - a for a, b in zip(L, L[1:]))


if __name__ == "__main__":
    t = stringToTreeNode("[2, 1, 3]")
    prettyPrintTree(t)
    print(Solution().getMinimumDifference(t))
예제 #2
0
def printParseTreeFromFile(infile):
    import utils
    utils.prettyPrintTree(_parseFile(infile))
예제 #3
0
def printAstFromFile(infile):
    import utils
    utils.prettyPrintTree(_genAstFromFile(infile))
예제 #4
0
from typing import List
from utils import TreeNode, prettyPrintTree


class Solution:
    def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
        if len(preorder) == 0:
            return None
        mid = inorder.index(preorder[0])
        t = TreeNode(preorder[0])
        t.left = self.buildTree(preorder[1:mid + 1], inorder[:mid])
        t.right = self.buildTree(preorder[mid + 1:], inorder[mid + 1:])
        return t


if __name__ == "__main__":
    preorder = [3, 9, 20, 15, 7]
    inorder = [9, 3, 15, 20, 7]
    prettyPrintTree(Solution().buildTree(preorder, inorder))