Exemplo n.º 1
0
 def invertTree(self, root: TreeNode) -> TreeNode:
     if root is None:
         return None
     root.left, root.right = root.right, root.left
     if root.left:
         root.left = self.invertTree(root.left)
     if root.right:
         root.right = self.invertTree(root.right)
     return root
Exemplo n.º 2
0
 def add(root: TreeNode, new: TreeNode) -> TreeNode:
     if new.val < root.val:
         if root.left is None:
             root.left = new
         else:
             root.left = add(root.left, new)
     else:
         if root.right is None:
             root.right = new
         else:
             root.right = add(root.right, new)
     return root
Exemplo n.º 3
0
 def bstFromPreorder(self, preorder: List[int]) -> TreeNode:
     root = TreeNode(preorder[0])
     current = root
     left_nodes = []  # nodes from which we descended to the left
     for val in preorder[1:]:
         node = TreeNode(val)
         if val < current.val:
             left_nodes.append(current)
             current.left = node
             current = current.left
         else:
             while len(left_nodes) > 0 and left_nodes[-1].val < val:
                 current = left_nodes.pop(-1)
             current.right = node
             current = current.right
     return root
Exemplo n.º 4
0
def _minimal_height(array, btree):
    if len(array) == 0:
        return
    else:
        mid_index = get_mid_index(array)
        node = TreeNode(value=array[mid_index])

        if node.visited:
            return
        else:
            node.visited = True
            btree.insert(node)
            slice_right = array[:mid_index] if len(array) > 1 else []
            _minimal_height(slice_right, btree)
            slice_left = array[mid_index + 1:] if len(array) > 1 else []
            _minimal_height(slice_left, btree)
Exemplo n.º 5
0
    def bstFromPreorder(self, preorder: List[int]) -> TreeNode:
        def add(root: TreeNode, new: TreeNode) -> TreeNode:
            if new.val < root.val:
                if root.left is None:
                    root.left = new
                else:
                    root.left = add(root.left, new)
            else:
                if root.right is None:
                    root.right = new
                else:
                    root.right = add(root.right, new)
            return root

        root = TreeNode(preorder[0])
        for child in preorder[1:]:
            node = TreeNode(child)
            root = add(root, node)
        return root
Exemplo n.º 6
0
def minimal_height(sorted_array):
    mid_index = get_mid_index(sorted_array)
    root = TreeNode(value=sorted_array[mid_index])
    btree = BinaryTree(root)

    _minimal_height(sorted_array[:mid_index], btree)
    shift_factor = 1 if len(sorted_array) > 1 else 0
    _minimal_height(sorted_array[mid_index + shift_factor:], btree)

    return btree
class Solution:
    def diameterOfBinaryTree(self, root: TreeNode) -> int:
        def depths(node: TreeNode) -> (int, int):
            if node is None:
                return (0, 0)
            depth_l = 0
            depth_r = 0
            prev_max = 0
            if node.left is not None:
                lds = depths(node.left)
                depth_l = 1 + lds[0]
                prev_max = lds[1]
            if node.right is not None:
                rds = depths(node.right)
                depth_r = 1 + rds[0]
                prev_max = max(prev_max, rds[1])
            return (max(depth_l, depth_r), max(depth_l + depth_r, prev_max))

        return depths(root)[1]


if __name__ == "__main__":
    testdata = [([1, [2, [4, None, None], [5, None, None]], [3, None, None]], 3)]
    testlib.run(
        lambda t, tc: t.assertEqual(
            Solution().diameterOfBinaryTree(TreeNode.from_list(tc[0])), tc[1], tc
        ),
        testdata,
    )
        right_depth = 0
        node = root
        while node is not None:
            left_depth += 1
            node = node.left
        node = root
        while node is not None:
            right_depth += 1
            node = node.right
        if left_depth == right_depth:
            return (1 << left_depth) - 1
        else:
            return 1 + self.countNodes(root.left) + self.countNodes(root.right)


if __name__ == "__main__":
    testdata = [
        ([1, None, None], 1),
        ([1, [2, None, None], None], 2),
        ([1, [2, None, None], [3, None, None]], 3),
        ([1, [2, [4, None, None], [5, None, None]], [3, [6, None, None], None]], 6),
        ([1, [2, [3, None, None], None], None], 3),
    ]
    testlib.run(
        lambda t, tc: t.assertEqual(
            Solution().countNodes(TreeNode.from_list(tc[0])), tc[1], tc
        ),
        testdata,
    )

Exemplo n.º 9
0
            return None
        root.left, root.right = root.right, root.left
        if root.left:
            root.left = self.invertTree(root.left)
        if root.right:
            root.right = self.invertTree(root.right)
        return root


if __name__ == "__main__":
    testdata = [(
        [
            4,
            [2, [1, None, None], [3, None, None]],
            [7, [6, None, None], [9, None, None]],
        ],
        [
            4,
            [7, [9, None, None], [6, None, None]],
            [2, [3, None, None], [1, None, None]],
        ],
    )]
    testlib.run(
        lambda t, tc: t.assertEqual(
            Solution().invertTree(TreeNode.from_list(tc[0])),
            TreeNode.from_list(tc[1]),
            tc,
        ),
        testdata,
    )
Exemplo n.º 10
0
# output (serialized tree format) as [], not null.

import testlib
from datastructures import TreeNode


class Solution:
    def searchBST(self, root: TreeNode, val: int) -> TreeNode:
        cur = root
        while cur is not None and cur.val != val:
            if cur.val > val:
                cur = cur.left
            else:
                cur = cur.right
        return cur


if __name__ == "__main__":
    testdata = [(
        [4, [2, [1, None, None], [3, None, None]], [7, None, None]],
        2,
        [2, [1, None, None], [3, None, None]],
    )]
    testlib.run(
        lambda t, tc: t.assertEqual(
            Solution().searchBST(TreeNode.from_list(tc[0]), tc[1]),
            TreeNode.from_list(tc[2]),
        ),
        testdata,
    )
Exemplo n.º 11
0
        todo = [(root, None, 0)]
        while not x_found or not y_found:
            (node, parent, depth) = todo.pop(0)
            if node.val == x:
                x_found = True
                x_parent = parent
                x_depth = depth
            if node.val == y:
                y_found = True
                y_parent = parent
                y_depth = depth
            if node.left is not None:
                todo.append((node.left, node.val, depth + 1))
            if node.right is not None:
                todo.append((node.right, node.val, depth + 1))
        return x_depth == y_depth and x_parent != y_parent


if __name__ == "__main__":
    testdata = [
        ([1, [2, [4, None, None], None], [3, None, None]], 4, 3, False),
        ([1, [2, None, [4, None, None]], [3, None, [5, None, None]]], 5, 4, True),
        ([1, [2, None, [4, None, None]], [3, None, None]], 2, 3, False),
    ]
    testlib.run(
        lambda t, tc: t.assertEqual(
            Solution().isCousins(TreeNode.from_list(tc[0]), tc[1], tc[2]), tc[3], tc
        ),
        testdata,
    )
Exemplo n.º 12
0
                current.left = node
                current = current.left
            else:
                while len(left_nodes) > 0 and left_nodes[-1].val < val:
                    current = left_nodes.pop(-1)
                current.right = node
                current = current.right
        return root


if __name__ == "__main__":
    testdata = [
        (
            [8, 5, 1, 7, 10, 12],
            TreeNode.from_list([
                8, [5, [1, None, None], [7, None, None]],
                [10, None, [12, None, None]]
            ]),
        ),
        ([8, 5, 10], TreeNode.from_list([8, [5, None, None], [10, None,
                                                              None]])),
        ([8], TreeNode.from_list([8, None, None])),
        ([8, 10], TreeNode.from_list([8, None, [10, None, None]])),
        (
            [8, 5, 1, 7],
            TreeNode.from_list(
                [8, [5, [1, None, None], [7, None, None]], None]),
        ),
    ]
    testlib.run(
        lambda t, tc: t.assertEqual(Solution().bstFromPreorder(tc[0]), tc[1],
                                    tc),
Exemplo n.º 13
0
            return max(out)
        return out[0]


if __name__ == "__main__":
    testdata = [
        ([1, [2, None, None], [3, None, None]], 6),
        ([-10, [9, None, None], [20, [15, None, None], [7, None, None]]], 42),
        ([-3, None, None], -3),
        (
            [
                9,
                [6, None, None],
                [
                    -3,
                    [-6, None, None],
                    [
                        2, [2, [-6, [-6, None, None], None], [-6, None, None]],
                        None
                    ],
                ],
            ],
            16,
        ),
    ]
    testlib.run(
        lambda t, tc: t.assertEqual(
            Solution().maxPathSum(TreeNode.from_list(tc[0])), tc[1], tc),
        testdata,
    )
Exemplo n.º 14
0
class Solution:
    def kthSmallest(self, root: TreeNode, k: int) -> int:
        seen: List[int] = []
        todo: List[TreeNode] = [root]
        while todo:
            node = todo.pop(0)
            if node.left is not None:
                todo.append(node.left)
            if node.right is not None:
                todo.append(node.right)
            pos = bisect.bisect_right(seen, node.val)
            if pos < k:
                seen.insert(pos, node.val)
            if len(seen) > k:
                seen.pop(-1)
        return seen[k - 1]


if __name__ == "__main__":
    testdata = [
        ([3, [1, None, [2, None, None]], [4, None, None]], 1, 1),
        ([5, [3, [2, [1, None, None], None], [4, None, None]], [6, None, None]], 3, 3),
    ]
    testlib.run(
        lambda t, tc: t.assertEqual(
            Solution().kthSmallest(TreeNode.from_list(tc[0]), tc[1]), tc[2], tc
        ),
        testdata,
    )
Exemplo n.º 15
0
    testdata = [
        (
            [
                0,
                [1, [0, None, [1, None, None]], [1, [0, None, None], [0, None, None]]],
                [0, [0, None, None], None],
            ],
            [0, 1, 0, 1],
            True,
        ),
        (
            [
                3,
                None,
                [
                    7,
                    [6, None, [4, None, [6, None, None]]],
                    [8, [1, [4, None, None], None], None],
                ],
            ],
            [3, 7, 6, 4, 6],
            True,
        ),
    ]
    testlib.run(
        lambda t, tc: t.assertEqual(
            Solution().isValidSequence(TreeNode.from_list(tc[0]), tc[1]), tc[2], tc
        ),
        testdata,
    )