# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right

import sys
sys.path = sys.path = ['.', '../', '../../'] + sys.path

from util import TreeNode, deserializeTree
from typing import List
from collections import defaultdict


class Solution:
    def averageOfLevels(self, root: TreeNode) -> List[float]:
        if not root:
            return []
        queue = [(0, root)]
        val_map, num_map = defaultdict(int), defaultdict(int)
        for lv, node in queue:
            val_map[lv] += node.val
            num_map[lv] += 1
            queue += [(lv + 1, node.left)] if node.left else []
            queue += [(lv + 1, node.right)] if node.right else []
        return [val_map[lv] / num_map[lv] for lv in val_map]


# [3.00000,14.50000,11.00000]
print(Solution().averageOfLevels(deserializeTree("[3, 9, 20, 15, 7]")))
Example #2
0
"""

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right

import sys
sys.path = ['.', '../', '../../'] + sys.path

from util import TreeNode, deserializeTree

class Solution:
    def sumRootToLeaf(self, root: TreeNode) -> int:
        if not root:
            return 0
        ans, stack = 0, [(root, 0)]
        while stack:
            node, curr_sum = stack.pop()
            curr_sum += node.val
            ans += curr_sum if not node.left and not node.right else 0
            stack += [(node.left, curr_sum << 1)] if node.left else []
            stack += [(node.right, curr_sum << 1)] if node.right else []
        return ans

# 22
print(Solution().sumRootToLeaf(deserializeTree("[1, 0, 1, 0, 1, 0, 1]")))

Example #3
0
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right

import sys
sys.path  = sys.path = ['.', '../', '../../'] + sys.path

from util import TreeNode, deserializeTree

class Solution:
    def rangeSumBST(self, root: TreeNode, low: int, high: int) -> int:
        if not root:
            return 0
        if low <= root.val <= high:
            return root.val + self.rangeSumBST(root.left, low, high) + self.rangeSumBST(root.right, low, high)
        elif root.val < low:
            return self.rangeSumBST(root.right, low, high)
        else:
            return self.rangeSumBST(root.left, low, high)

# 32
print(Solution().rangeSumBST(deserializeTree("[10, 5, 15, 3, 7, null, 18]"), 7, 15))

# 23
print(Solution().rangeSumBST(deserializeTree("[10, 5, 15, 3, 7, 13, 18, 1, null, 6]"), 6, 10))

Example #4
0

class Solution:
    def increasingBST(self, root: TreeNode) -> TreeNode:
        ans, curr = None, None

        def traverse(tree):
            nonlocal ans, curr
            if not tree:
                return
            traverse(tree.left)
            if ans:
                curr.right = TreeNode(tree.val)
                curr = curr.right
            else:
                ans = curr = TreeNode(tree.val)
            traverse(tree.right)

        traverse(root)
        return ans


# [1, null, 2, null, 3, null, 4, null, 5, null, 6, null, 7, null, 8, null, 9]
print(
    serializeTree(Solution().increasingBST(
        deserializeTree(
            "[5, 3, 6, 2, 4, null, 8, 1, null, null, null, 7, 9]"))))

# [1, null, 5, null, 7]
print(serializeTree(Solution().increasingBST(deserializeTree("[5, 1, 7]"))))
Example #5
0
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right

import sys
sys.path = ['.', '../', '../../'] + sys.path

from util import TreeNode, deserializeTree

class Solution:
    def minDepth(self, root: TreeNode) -> int:
        if not root:
            return 0
        queue = [(root, 1)]
        while queue:
            node, level = queue.pop(0)
            if not node.left and not node.right:
                return level
            queue += [(node.left, level + 1)] if node.left else []
            queue += [(node.right, level + 1)] if node.right else []

# 2
print(Solution().minDepth(deserializeTree("[3,9,20,null,null,15,7]")))

# 5
print(Solution().minDepth(deserializeTree("[2,null,3,null,4,null,5,null,6]")))

Example #6
0
            return root
        if root.val == key:
            if not root.left:
                return root.right
            elif not root.right:
                return root.left
            else:
                # Find successor
                succ = root.right
                while succ and succ.left:
                    succ = succ.left
                root.val = succ.val
                root.right = self.deleteNode(root.right, succ.val)
        elif key < root.val:
            root.left = self.deleteNode(root.left, key)
        else:
            root.right = self.deleteNode(root.right, key)
        return root

# "[5, 4, 6, 2, null, null, 7]"
print(serializeTree(Solution().deleteNode(deserializeTree("[5, 3, 6, 2, 4, null, 7]"), 3)))

# "[5, 3, 6, 2, 4, null, 7]"
print(serializeTree(Solution().deleteNode(deserializeTree("[5, 3, 6, 2, 4, null, 7]"), 0)))

# "[]"
print(serializeTree(Solution().deleteNode(deserializeTree("[]"), 0)))

# "[6, 3, 7, 2, 4]"
print(serializeTree(Solution().deleteNode(deserializeTree("[5, 3, 6, 2, 4, null, 7]"), 5)))
Example #7
0
import sys

sys.path = sys.path = ['.', '../', '../../'] + sys.path

from util import TreeNode, deserializeTree


class Solution:
    def findTilt(self, root: TreeNode) -> int:
        def solve(tree):
            if not tree:
                return [0, 0]
            left_sum, left_tilt = solve(tree.left) if tree.left else [0, 0]
            right_sum, right_tilt = solve(tree.right) if tree.right else [0, 0]
            return [
                left_sum + right_sum + tree.val,
                left_tilt + right_tilt + abs(left_sum - right_sum)
            ]

        return solve(root)[1]


# 1
print(Solution().findTilt(deserializeTree("[1, 2, 3]")))

# 15
print(Solution().findTilt(deserializeTree("[4, 2, 9, 3, 5, null, 7]")))

# 9
print(Solution().findTilt(deserializeTree("[21, 7, 14, 1, 1, 2, 2, 3, 3]")))
Example #8
0
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right

import sys
sys.path = sys.path = ['.', '../', '../../'] + sys.path

from util import TreeNode, deserializeTree


class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        if not root:
            return 0
        return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))


# 3
print(Solution().maxDepth(deserializeTree("[3, 9, 20, null, null, 15, 7]")))

# 2
print(Solution().maxDepth(deserializeTree("[1, null, 2]")))

# 0
print(Solution().maxDepth(deserializeTree("[]")))

# 1
print(Solution().maxDepth(deserializeTree("[0]")))
Example #9
0
sys.path = ['.', '../', '../../'] + sys.path

from util import TreeNode, serializeTree, deserializeTree

class Solution:
    def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode:
        if not root:
            return TreeNode(val)
        if val < root.val:
            root.left = self.insertIntoBST(root.left, val)
        else:
            root.right = self.insertIntoBST(root.right, val)
        return root

# [4, 2, 7, 1, 3, 5]
print(serializeTree(Solution().insertIntoBST(
    deserializeTree("[4, 2, 7, 1, 3]"), 5)))

# [40, 20, 60, 10, 30, 50, 70, null, null, 25]
print(serializeTree(Solution().insertIntoBST(
    deserializeTree("[40, 20, 60, 10, 30, 50, 70]"), 25)))

# [4, 2, 7, 1, 3, 5]
print(serializeTree(Solution().insertIntoBST(
    deserializeTree("[4, 2, 7, 1, 3, null, null, null, null, null, null]"), 5)))

# [5]
print(serializeTree(Solution().insertIntoBST(
    deserializeTree("[]"), 5)))

import sys
sys.path = ['.', '../', '../../'] + sys.path

from util import TreeNode, deserializeTree, serializeTree


class Solution:
    def addOneRow(self, root: TreeNode, val: int, depth: int) -> TreeNode:
        dummy = TreeNode(0, root)
        row = [dummy]
        for _ in range(depth - 1):
            row = [
                child for node in row for child in [node.left, node.right]
                if child
            ]
        for node in row:
            node.left = TreeNode(val, node.left, None)
            node.right = TreeNode(val, None, node.right)
        return dummy.left


# [4, 1, 1, 2, null, null, 6, 3, 1, 5]
print(
    serializeTree(Solution().addOneRow(deserializeTree("[4, 2, 6, 3, 1, 5]"),
                                       1, 2)))

# [4, 2, null, 1, 1, 3, null, null, 1]
print(
    serializeTree(Solution().addOneRow(deserializeTree("[4, 2, null, 3, 1]"),
                                       1, 3)))
Example #11
0
class Solution:
    def trimBST(self, root: TreeNode, low: int, high: int) -> TreeNode:
        if root:
            if root.val < low:
                root = self.trimBST(root.right, low, high)
            elif root.val > high:
                root = self.trimBST(root.left, low, high)
            else:
                root.left = self.trimBST(root.left, low, high)
                root.right = self.trimBST(root.right, low, high)
        return root


# [1, null, 2]
print(serializeTree(Solution().trimBST(deserializeTree("[1, 0, 2]"), 1, 2)))

# [3, 2, null, 1]
print(
    serializeTree(Solution().trimBST(
        deserializeTree("[3, 0, 4, null, 2, null, null, 1]"), 1, 3)))

# [1]
print(serializeTree(Solution().trimBST(deserializeTree("[1]"), 1, 2)))

# [1, null, 2]
print(serializeTree(Solution().trimBST(deserializeTree("[1, null, 2]"), 1, 3)))

# [2]
print(serializeTree(Solution().trimBST(deserializeTree("[1, null, 2]"), 2, 4)))

class Solution:
    def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode:
        if not root:
            return TreeNode(val)
        if val < root.val:
            root.left = self.insertIntoBST(root.left, val)
        else:
            root.right = self.insertIntoBST(root.right, val)
        return root


# [4, 2, 7, 1, 3, 5]
print(
    serializeTree(Solution().insertIntoBST(deserializeTree("[4, 2, 7, 1, 3]"),
                                           5)))

# [40, 20, 60, 10, 30, 50, 70, null, null, 25]
print(
    serializeTree(Solution().insertIntoBST(
        deserializeTree("[40, 20, 60, 10, 30, 50, 70]"), 25)))

# [4, 2, 7, 1, 3, 5]
print(
    serializeTree(Solution().insertIntoBST(
        deserializeTree("[4, 2, 7, 1, 3, null, null, null, null, null, null]"),
        5)))

# [5]
print(serializeTree(Solution().insertIntoBST(deserializeTree("[]"), 5)))