Beispiel #1
0
    #
    #     if root:
    #         root.right, root.left = root.left, root.right
    #         if root.right:
    #             self.flatten(root.right)
    #         else:
    #             self.cur = root
    #         if root.left:
    #             self.cur.right = root.left
    #             root.left = None
    #             self.flatten(self.cur.right)

    # A more clever solution
    def __init__(self):
        self.prev = None

    def flatten(self, root):
        if not root:
            return None
        self.flatten(root.right)
        self.flatten(root.left)

        root.right = self.prev
        root.left = None
        self.prev = root
        return root


x = create_tree([[1], [2, 5], [3, 4, None, 6]])
Solution().flatten(x)
x.print_all()
from typing import List, Optional

from TreeNode import create_tree, TreeNode


class Solution:
    def findFrequentTreeSum(self, root: Optional[TreeNode]) -> List[int]:
        freq = {}

        def analysis(node):
            if not node:
                return 0
            tot = analysis(node.left) + analysis(node.right) + node.val
            freq[tot] = freq.get(tot, 0) + 1
            return tot

        analysis(root)
        max_freq = max(freq.values())
        return [i for i in freq if freq[i] == max_freq]


if __name__ == '__main__':
    print(Solution().findFrequentTreeSum(create_tree([5, 2, -3])))
Beispiel #3
0
from typing import Optional
from TreeNode import TreeNode, create_tree


class Solution:
    def addOneRow(self, root: Optional[TreeNode], val: int,
                  depth: int) -> Optional[TreeNode]:
        if depth == 1:
            return TreeNode(val, left=root)
        q = deque([root])
        l = 1
        for _ in range(depth - 2):
            cnt = 0
            for i in range(l):
                cur = q.popleft()
                if cur.left:
                    cnt += 1
                    q.append(cur.left)
                if cur.right:
                    cnt += 1
                    q.append(cur.right)
            l = cnt
        for i in q:
            i.left = TreeNode(val, left=i.left)
            i.right = TreeNode(val, right=i.right)
        return root


if __name__ == '__main__':
    print(Solution().addOneRow(create_tree([1, 2, 3, 4]), 5, 4))
        #             to_point.next = cur.left or cur.right
        #         if cur.left:
        #             cur.left.next = cur.right
        #         to_point = cur.right or cur.left or to_point
        #         cur = cur.next
        #     while root:
        #         if root.left or root.right:
        #             root = root.left or root.right
        #             break
        #         root = root.next
        # return saveroot

        # A more clever way using sentinel
        sentinel = tail = Node(0)
        saveroot = root
        while root:
            tail.next = root.left
            if tail.next:
                tail = tail.next
            tail.next = root.right
            if tail.next:
                tail = tail.next
            root = root.next
            if not root:
                tail = sentinel
                root = sentinel.next
        return saveroot


Solution().connect(create_tree([[1], [2, 3], [4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14, 15]], Node))
        first: Optional[TreeNode] = None
        second: Optional[TreeNode] = None

        def find_swap():
            nonlocal prev, first, second
            if prev and prev.val > root.val:
                second = root
                if not first:
                    first = prev
            prev = root

        while root:
            if not root.left:
                find_swap()
                root = root.right
            else:
                pred = root.left
                while pred.right and pred.right != root:
                    pred = pred.right
                if not pred.right:
                    pred.right = root
                    root = root.left
                else:
                    pred.right = None
                    find_swap()
                    root = root.right
        first.val, second.val = second.val, first.val


Solution().recoverTree(create_tree([[1], [3, None], [None, 2, None, None]]))
        def rec(node, acc):
            if not node:
                return 0
            right = rec(node.right, acc)
            node.val += right + acc
            left = rec(node.left, node.val)
            return node.val + left - acc

        rec(root, 0)
        return root

    def convertBST2(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        tot = 0

        def rec(node):
            if node:
                nonlocal tot
                rec(node.right)
                tot += node.val
                node.val = tot
                rec(node.left)

        rec(root)
        return root


if __name__ == '__main__':
    print(Solution().convertBST(
        create_tree(
            [4, 1, 6, 0, 2, 5, 7, None, None, None, 3, None, None, None, 8])))
Beispiel #7
0
from TreeNode import TreeNode, create_tree


class Solution:
    def isValidBST(self, root: TreeNode) -> bool:
        def rec(node, inf, sup):
            if not node:
                return True
            if node.val <= inf or node.val >= sup:
                return False
            if not rec(node.left, inf, node.val):
                return False
            if not rec(node.right, node.val, sup):
                return False
            return True

        return rec(root, -float('inf'), float('inf'))


print(Solution().isValidBST(create_tree([[5], [4, 6], [None, None, 3, 7]])))
            else:
                if node.left:
                    cur = node.left
                    if cur.right:
                        while cur.right:
                            predecessor = cur
                            cur = cur.right
                        predecessor.right = None
                        node.val = cur.val
                    else:
                        node.val = node.left.val
                        node.left = node.left.left
                else:
                    cur = node.right
                    if cur.left:
                        while cur.left:
                            predecessor = cur
                            cur = cur.left
                        predecessor.left = None
                        node.val = cur.val
                    else:
                        node.val = node.right.val
                        node.right = node.right.right

        rebalance(target, prev)
        return sentinel.left


if __name__ == '__main__':
    Solution().deleteNode(create_tree([[5], [3, 6], [2, 4, None, 7]]), 5).print_all()
    def next(self):
        """
        :rtype: int
        """
        while self.current_node:
            self.stack.append(self.current_node)
            self.current_node = self.current_node.left
        next = self.stack.pop()
        self.current_node = next.right
        return next.val


if __name__ == '__main__':
    # Your BSTIterator object will be instantiated and called as such:
    tree = create_tree([[1], [2, 3], [4, 5, 6, 7]])
    obj = BSTIterator(tree)
    print(obj.hasNext())
    print(obj.next())
    print(obj.hasNext())
    print(obj.next())
    print(obj.hasNext())
    print(obj.next())
    print(obj.hasNext())
    print(obj.next())
    print(obj.hasNext())
    print(obj.next())
    print(obj.hasNext())
    print(obj.next())
    print(obj.hasNext())
    print(obj.next())
Beispiel #10
0
                paths.append(cur.copy())
        if node.left:
            rec(node.left, total - node.val)
        if node.right:
            rec(node.right, total - node.val)
        cur.pop()

    rec(root, n)
    return paths

# This approach doesn't work because paths gets 2 identical cur when reaching leaves
# def find_path2(root: TreeNode, n):
#     paths = []
#     cur = []
#
#     def rec(node, total):
#         if not node:
#             if total == 0:
#                 paths.append(cur.copy())
#         else:
#             cur.append(node.val)
#             rec(node.left, total - node.val)
#             rec(node.right, total - node.val)
#             cur.pop()
#
#     rec(root, n)
#     return paths


print(find_path(create_tree([[5], [4, 8], [11, None, 13, 4], [7, 2, None, None, None, None, 5, 1]]), 22))