def build(preorder, inorder, pp, pr, ip, ir):
    if pp > pr: return None
    root = TreeNode(preorder[pp])
    index = inorder.index(root.val)
    root.left = build(preorder, inorder, pp + 1, pp - ip + index, ip, index - 1)
    root.right = build(preorder, inorder, pr - ir + index + 1, pr, index + 1, ir)
    return root
def sortedArrayToBST(num):
    if not num: return None
    mid = len(num) / 2
    root = TreeNode(num[mid])
    root.left = sortedArrayToBST(num[:mid])
    root.right = sortedArrayToBST(num[mid + 1:])
    return root
def create_tree(array):
    length = len(array)
    root = TreeNode(array[length / 2])

    root.left_child, root.right_child = get_child(
        array[:length / 2]), get_child(array[length / 2 + 1:])
    return root
Esempio n. 4
0
def sortedArrayToBST(num):
    if not num: return None
    mid = len(num) / 2
    root = TreeNode(num[mid])
    root.left = sortedArrayToBST(num[:mid])
    root.right = sortedArrayToBST(num[mid + 1:])
    return root
def build(inorder, postorder, ip, ir, pp, pr):
    if ip > ir: return None
    root = TreeNode(postorder[pr])
    index = inorder.index(postorder[pr])
    root.left = build(inorder, postorder, ip, index - 1, pp, pp - ip + index - 1)
    root.right = build(inorder, postorder, index + 1, ir, pr - ir + index, pr - 1)
    return root
Esempio n. 6
0
def createTree():
    root = T_Node(100)
    root.left = T_Node(98)
    root.right = T_Node(102)
    root.left.left = T_Node(96)
    root.left.right = T_Node(99)
    root.left.left.right = T_Node(97)
    return root
 def helper(bound=None):
     if not inorder or inorder[0] == bound:
         return None
     root = TreeNode(preorder.popleft())
     root.left = helper(root.val)
     inorder.popleft()
     root.right = helper(bound)
     return root
Esempio n. 8
0
def createBST(arr, start, end):
    if start > end:
        return None
    mid = int((start + end) / 2)
    node = TreeNode(arr[mid])
    node.left = createBST(arr, start, mid - 1)
    node.right = createBST(arr, mid + 1, end)
    return node
Esempio n. 9
0
def sortedArrayToBST(nums):
    if not nums:
        return None
    mid = len(nums) // 2
    root = TreeNode(nums[mid])
    root.left = sortedArrayToBST(nums[0:mid])
    root.right = sortedArrayToBST(nums[mid + 1:])
    return root
Esempio n. 10
0
 def helper(left, right):
     if left > right:
         return None
     mid = (left + right) >> 1
     node = TreeNode(nums[mid])
     node.left = helper(left, mid - 1)
     node.right = helper(mid + 1, right)
     return node
Esempio n. 11
0
def build(preorder, inorder, pp, pr, ip, ir):
    if pp > pr: return None
    root = TreeNode(preorder[pp])
    index = inorder.index(root.val)
    root.left = build(preorder, inorder, pp + 1, pp - ip + index, ip,
                      index - 1)
    root.right = build(preorder, inorder, pr - ir + index + 1, pr, index + 1,
                       ir)
    return root
Esempio n. 12
0
    def addQuestion(self):
        """Adds question and two answers"""
        question = raw_input("What would you ask?")
        self.rootR.setValue(question)
        y = raw_input("What would the yes answer be? write in question form")
        n = raw_input("what would the no answer be? write in quation form")

        self.rootR.left = TreeNode(n)
        self.rootR.right = TreeNode(y)
Esempio n. 13
0
 def helper(left, right):
     if left > right:
         return None
     # 总是选择中间位置左边的数字作为根节点
     mid = left + (right - left) // 2
     root = TreeNode(nums[mid])
     root.left = helper(left, mid - 1)
     root.right = helper(mid + 1, right)
     return root
Esempio n. 14
0
 def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode:
     if not root:
         node = TreeNode(val)
         return node
     if val > root.val:
         root.right = self.insertIntoBST(root.right, val)
     elif val < root.val:
         root.left = self.insertIntoBST(root.left, val)
     return root
Esempio n. 15
0
def _simpleTest(canv):
  from Tree import TreeNode as Node
  root = Node(None,'r',label='r')
  c1 = root.AddChild('l1_1',label='l1_1')
  c2 = root.AddChild('l1_2',isTerminal=1,label=1)
  c3 = c1.AddChild('l2_1',isTerminal=1,label=0)
  c4 = c1.AddChild('l2_2',isTerminal=1,label=1)

  DrawTreeNode(root,(150,visOpts.vertOffset),canv)  
 def trimBST(self, root: TreeNode, low: int, high: int) -> TreeNode:
     if root is None:
         return root
     if root.val > high:
         return self.trimBST(root.left, low, high)
     if root.val < low:
         return self.trimBST(root.right, low, high)
     root.left = self.trimBST(root.left, low, high)
     root.right = self.trimBST(root.right, low, high)
     return root
Esempio n. 17
0
    def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:
        if not t1:
            return t2
        if not t2:
            return t1

        merged = TreeNode(t1.val + t2.val)
        merged.left = self.mergeTrees(t1.left, t2.left)
        merged.right = self.mergeTrees(t1.right, t2.right)
        return merged
Esempio n. 18
0
def add_nodes(root, nodes):
    for i in range(0, len(nodes)):
        if nodes[i][0] == root.gfv():
            root.addChild(
                add_nodes(TreeNode(nodes[i], 0), nodes[0:i] + nodes[i + 1:]))
        elif nodes[i][1] == root.gfv():
            root.addChild(
                add_nodes(TreeNode(nodes[i], 1), nodes[0:i] + nodes[i + 1:]))

    return root
Esempio n. 19
0
 def buildTree(left, right):
     if left > right:
         return None
     mid = (left + right) >> 1
     root = TreeNode()
     root.left = buildTree(left, mid - 1)
     nonlocal head
     root.val = head.val
     head = head.next
     root.right = buildTree(mid + 1, right)
     return root
        def helper(inorder_left, inorder_right):
            if inorder_left > inorder_right:
                return None
            val = postorder.pop()
            root = TreeNode(val)

            # 右子树结点个数
            index = indexs[val]
            root.right = helper(index + 1, inorder_right)
            root.left = help(inorder_left, index - 1)
            return root
def convert(size):
    if size < 1: return None
    global curr
    # Recursively construct the left subtree of half size of the current tree.
    left = convert(size / 2)
    # Create the root for the current tree.
    root = TreeNode(curr.val)
    root.left = left
    # Move the pointer and recursively construct the right subtree.
    curr = curr.next
    root.right = convert(size - size / 2 - 1)
    return root
Esempio n. 22
0
def mergeTrees(t1: TreeNode, t2: TreeNode) -> TreeNode:
    if (t1 is None and t2 is None):
        return None
    if (t1 is None):
        return t2
    if (t2 is None):
        return t1
    else:
        node = TreeNode(t1.val + t2.val)
        node.left = mergeTrees(t1.left, t2.left)
        node.right = mergeTrees(t1.right, t2.right)
        return node
        def helper(preorder_left, preorder_right, inorder_left, inorder_right):
            if preorder_left > preorder_right:
                return None
            preorder_root = preorder_left
            inorder_root = indexs[preorder[preorder_root]]

            root = TreeNode(preorder[preorder_root])
            # 左子树结点个数
            size_left_subtree = inorder_root - inorder_left
            root.left = helper(preorder_left + 1, preorder_left + size_left_subtree, inorder_left, inorder_root - 1)
            root.right = helper(preorder_left + size_left_subtree + 1, preorder_right, inorder_root + 1, inorder_right)
            return root
Esempio n. 24
0
def convert(size):
    if size < 1: return None
    global curr
    # Recursively construct the left subtree of half size of the current tree.
    left = convert(size / 2)
    # Create the root for the current tree.
    root = TreeNode(curr.val)
    root.left = left
    # Move the pointer and recursively construct the right subtree.
    curr = curr.next
    root.right = convert(size - size / 2 - 1)
    return root
Esempio n. 25
0
    def mergeTrees(self, root1: TreeNode, root2: TreeNode) -> TreeNode:
        """
        合并二叉树
        """
        if not root1:
            return root2
        if not root2:
            return root1

        merged = TreeNode(root1.val + root2.val)
        merged.left = self.mergeTrees(root1.left, root2.left)
        merged.right = self.mergeTree(root1.right, root2.right)
        return merged
Esempio n. 26
0
 def deep(node: TreeNode, val: int):
     if val > node.val:
         if node.right:
             deep(node.right, val)
         else:
             node.right = TreeNode(val)
             return
     if val < node.val:
         if node.left:
             deep(node.left, val)
         else:
             node.left = TreeNode(val)
             return
 def dfs(node: TreeNode):
     if not node:
         return node
     if not node.left:
         node.right = dfs(node.right)
         return node
     tmp = node.right
     node.right = dfs(node.left)
     node.left = None
     tmp_f = node.right
     while tmp_f.right:
         tmp_f = tmp_f.right
     tmp_f.right = dfs(tmp)
     return node
    def buildTreeInner(
        l, r
    ):  # l, r are used as a way to track the size of subtree. Size of subtree - r - l + 1.
        nonlocal preorder_index
        if l > r:  # no elements for this subtree. So return
            return None
        node = TreeNode(preorder[preorder_index])
        index = inorder_map[preorder[preorder_index]]

        preorder_index += 1

        node.left = buildTreeInner(l, index - 1)
        node.right = buildTreeInner(index + 1, r)
        return node
def get_child(array):
    length = len(array)
    node = TreeNode(array[length / 2])

    if length == 1:
        return node

    if length == 2:
        node.left_child = get_child(array[:length / 2])
    else:
        node.left_child, node.right_child = get_child(
            array[:length / 2]), get_child(array[length / 2 + 1:])

    return node
Esempio n. 30
0
def read_recursion(inFile, currentNode):
    """First argument is the handle to the file being read, and
    the second is the current node.
    Pre: currentNode has been created already, and inFile refers to a
         valid file that has been opened for reading.
    Post: currentNode will either have no children if it is a guess
          or two children if it is a question. Either the guess or
          the question will be saved in its 'data' instance variable."""
    category = inFile.readline()
    
    # continue to read from the file, eating up white space. Note that
    # readline() includes the newline at the end of the line in the file.
    # hence the '\n' after each possible value for category.
    while category != "Guess:\n" and category != "Question:\n":
        category = inFile.readline()

    data = inFile.readline()
    currentNode.setValue( data )
    
    # check for base case. If we are not at a question, we are at the
    # guesses in the leaves.
    if category != "Question:\n":
        return
    
    # we know now that this is an internal node. Read the order of the
    # directions. These two instructions are only necessary for files that
    # follow the format in the assignment text. If you assume a specific
    # ordering of the data, all these checks are not necessary.
    firstChild = inFile.readline()
    while firstChild != "no\n":
	firstChild = inFile.readline()
    #firstChild = inFile.readline()
    secondChild = inFile.readline()
    
    # first create the necessary child and then pass it to the recursion
    if firstChild == "no\n":
        currentNode.left = TreeNode()
        read_recursion( inFile, currentNode.left )
    else:
        currentNode.right = TreeNode()
        read_recursion( inFile, currentNode.right )

    # go the other route next
    if secondChild == "no\n":
        currentNode.left = TreeNode()
        read_recursion( inFile, currentNode.left )
    else:
        currentNode.right = TreeNode()
        read_recursion( inFile, currentNode.right )
Esempio n. 31
0
    def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
        if len(inorder) == 0:
            return None

        root = TreeNode(postorder[-1])
        in_res = inorder.index(postorder[-1])
        left_inorder = inorder[:in_res]
        right_inorder = inorder[in_res + 1:]
        left_len = len(left_inorder)
        right_len = len(right_inorder)
        left_postorder = postorder[:left_len]
        right_postorder = postorder[-(1 + right_len):-1]
        root.left = self.buildTree(left_inorder, left_postorder)
        root.right = self.buildTree(right_inorder, right_postorder)
        return root
Esempio n. 32
0
 def recur(node: TreeNode):
     node.left, node.right = node.right, node.left
     if node.left:
         recur(node.left)
     if node.right:
         recur(node.right)
     return node
Esempio n. 33
0
def parseOpeningBrace():
    global count
    global input_tokens

    if (count == len(input_tokens)):
        print("Expected { but got ", input_tokens[count])
        return TreeNode(" ")

    elif (input_tokens[count] == "{"):
        openingBraceTree = TreeNode(input_tokens[count])
        count = count + 1
        return openingBraceTree

    else:
        print("Expected { but got ", input_tokens[count])
        sys.exit()
Esempio n. 34
0
    def allPossibleFBTInner(N) -> List[Optional[TreeNode]]:
        if N in mem:
            return mem[N]

        ans = []
        for x in range(N):
            y = N - 1 - x
            for left in allPossibleFBTInner(x):
                for right in allPossibleFBTInner(y):
                    bns = TreeNode(0)
                    bns.left = left
                    bns.right = right
                    ans.append(bns)

        mem[N] = ans
        return ans
Esempio n. 35
0
def miniHeightBST(item, start, end):
    if(start > end):
        return None
    mid = (start + end) / 2
    n = TreeNode(None,item[mid])
    n.leftChild = miniHeightBST(item,start,mid-1)
    n.rightChild = miniHeightBST(item,mid+1,end)
    return n

# Testing part...

#list = [1,2,3,4,5,6,7,8,9,10]


#root = miniHeightBST(list,0,len(list) - 1)

#root.printSubtree(5)
Esempio n. 36
0
#######################################
#Name: Test.py
#purpose: This tests to make sure the tree and the write function are working
#Author: Guillermo
#
##########################################


from Tree import TreeNode
import write_recursion 
sampleTree = TreeNode()

sampleTree.setValue(7)



sampleTree.addLeft(6)
sampleTree.addRight(10)
y = sampleTree.getLeft()
x = sampleTree.getRight()
x.addLeft(9)
x.addRight(57)

y.addLeft(8)
y.addRight(47)


def print_tree(tree):
                if tree == None: 
                        return
                print tree.item