示例#1
0
    def binary_tree_path_sum_helper(self, root, target):
        # write your code here
        if root is None:
            return []
        if root.left is None and root.right is None:
            if root.val == target:
                return [[target]]
            else:
                return []

        left_rslt = self.binary_tree_path_sum_helper(root.left,
                                                     target - root.val)
        right_rslt = self.binary_tree_path_sum_helper(root.right,
                                                      target - root.val)

        rslt = left_rslt + right_rslt
        for i in range(len(rslt)):
            rslt[i].append(root.val)

        return rslt


root = build_tree_breadth_first(sequence=[1, 2, 4, 2, 3])
sol = Solution()
rslt = sol.binaryTreePathSum(root=root, target=5)
print(rslt)

root = build_tree_breadth_first(sequence=[1, 2, -5, 4, None, 5, 6])
sol = Solution()
rslt = sol.binaryTreePathSum(root=root, target=2)
            prev.right = node

        return root


# method recursion
class Solution2:
    """
    @param: root: The root of the binary search tree.
    @param: node: insert this node into the binary search tree
    @return: The root of the new binary search tree.
    """
    def insertNode(self, root, node):
        root = self.traverse_and_try_insert(root, node)
        return root

    def traverse_and_try_insert(self, root, node):
        if root is None:
            return node
        if node.val < root.val:
            root.left = self.traverse_and_try_insert(root.left, node)
        else:
            root.right = self.traverse_and_try_insert(root.right, node)

        return root


sol = Solution2()
root = build_tree_breadth_first(sequence=[2, 1, 4, 3])
rslt = sol.insertNode(root, node=TreeNode(6))
示例#3
0
            if right_minsubtree_sum < right_subtree_sum + root.val:
                return right_subtree_sum + root.val, right_minsubtree_sum, right_minsubtree_root
            else:
                return right_subtree_sum + root.val, right_subtree_sum + root.val, root

        # both left and right subtree
        tree_sum = root.val + left_subtree_sum + right_subtree_sum
        if tree_sum <= left_minsubtree_sum and tree_sum <= right_minsubtree_sum:
            return tree_sum, tree_sum, root

        if left_minsubtree_sum <= tree_sum and left_minsubtree_sum <= right_minsubtree_sum:
            return tree_sum, left_minsubtree_sum, left_minsubtree_root

        if right_minsubtree_sum <= tree_sum and right_minsubtree_sum <= left_minsubtree_sum:
            return tree_sum, right_minsubtree_sum, right_minsubtree_root

        print("oops should not get here")


from helperfunc import build_tree_breadth_first

sol = Solution2()
root = build_tree_breadth_first([1, None, 2])
sol.findSubtree(root=root)

root = build_tree_breadth_first(sequence=[
    1, 1, -1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1
])
sol.findSubtree(root=root)
    def binaryTreePaths(self, root):
        # write your code here
        if root is None:
            return []

        paths = []
        this_path = [str(root.val)]
        self.dfs(root, this_path, paths)
        return paths

    def dfs(self, node, this_path, paths):
        if node.left is None and node.right is None:
            paths.append('->'.join(this_path))

        if node.left:
            this_path.append(str(node.left.val))
            self.dfs(node.left, this_path, paths)
            this_path.pop()

        if node.right:
            this_path.append(str(node.right.val))
            self.dfs(node.right, this_path, paths)
            this_path.pop()


from helperfunc import build_tree_breadth_first

sol = Solution3()
root = build_tree_breadth_first(sequence=[1, 2, 3, None, 5])
sol.binaryTreePaths(root=root)
            elif lca_left_tree and not lca_right_tree:
                return True, True, lca_left_tree
            elif not lca_left_tree and lca_right_tree:
                return True, True, lca_right_tree
            else:
                # if there are no lca in either subtree the lca must be root
                return True, True, root
        else:
            # if either of A or B does not exist in this tree. it means no LCA, so we return None for LCA.
            return a_exist_in_tree, b_exist_in_tree, None


from helperfunc import build_tree_breadth_first, TreeNode

sol = Solution()
root = build_tree_breadth_first([1, 2, 3, 4, 5, 6, 7])
A = root.left
B = root.right

rslt = sol.lowestCommonAncestor3(root, A, B)


class Solution:
    """
    @param: root: The root of the binary tree.
    @param: A: A TreeNode
    @param: B: A TreeNode
    @return: Return the LCA of the two nodes.
    """
    def lowestCommonAncestor3(self, root, A, B):
示例#6
0
        # If key is larger than root's key, go to right subtree
        elif p.val > root.val:
            self.pre = root
            self.helper(root.right, p)


class Solution2:

    def inorderPredecessor(self, root, p):
        self.pre = None
        self.dfs(root, p)
        return self.pre

    def dfs(self, root, p):
        if not root:
            return
        if root.val >= p.val:
            self.dfs(root.left, p)
        else:
            self.pre = root
            self.dfs(root.right, p)


from helperfunc import build_tree_breadth_first

root = build_tree_breadth_first([20, 1, 40, None, None, 35])
p = root.right.left

sol = Solution2()
sol.inorderPredecessor(root, p)
示例#7
0
from helperfunc import build_tree_breadth_first


class Solution3:
    """
    @param root: the given BST
    @param k: the given k
    @return: the kth smallest element in BST
    """
    def kthSmallest(self, root, k):
        self.val = None
        self.count = k
        # write your code here
        self.traverse(root)
        return self.val

    def traverse(self, root):
        if root is None:
            return
        self.traverse(root.left)
        self.count = self.count - 1
        if self.count == 0:
            self.val = root.val
            return
        self.traverse(root.right)


root = build_tree_breadth_first([5, 4, 9, 2, None, 8, 10])
sol = Solution3()
sol.kthSmallest(root, 3)
            prev_node.left = None
            prev_node.right = curr_node
            prev_node = curr_node

            if curr_node.right:
                stack.append(curr_node.right)
            if curr_node.left:
                stack.append(curr_node.left)

        return dummy_node.right


from helperfunc import TreeNode, build_tree_breadth_first

sol = Solution()
root = build_tree_breadth_first(sequence=[1, 2, 5, 3, 4, None, 6])
linked_list = sol.flatten(root)
"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""

from collections import deque


class SolutionOutOfMemory:
    """
    @param root: a TreeNode, the root of the binary tree
示例#9
0
    def binaryTreePathSum(self, root, target):
        # write your code here
        rslt = []
        curr_path = []
        curr_sum = 0
        self.dfs_helper(root, curr_path, curr_sum, rslt, target)
        return rslt

    def dfs_helper(self, node, curr_path, curr_sum, rslt, target):
        if node is None:
            return
        curr_path.append(node.val)
        curr_sum += node.val
        if curr_sum == target and node.left is None and node.right is None:
            rslt.append(curr_path[:])

        self.dfs_helper(node.left, curr_path, curr_sum, rslt, target)
        self.dfs_helper(node.right, curr_path, curr_sum, rslt, target)
        curr_path.pop()


from helperfunc import build_tree_breadth_first

sol = Solution()
root = build_tree_breadth_first(
    [1, 1, 1, 3, 4, 4, 3, None, None, 1, None, 5, 7])
assert sol.binaryTreePathSum(root, target=6) == []

root = build_tree_breadth_first([1, 2, 4, 2, 3])
assert sol.binaryTreePathSum(root, target=5) == [[1, 2, 2], [1, 4]]
示例#10
0
    @return: True if there has next node, or false
    """

    def hasNext(self, ):
        return len(self.stack) > 0

    """
    @return: return next node
    """

    def next(self, ):
        node = self.stack.pop()
        node_to_return = node
        if node.right:
            node = node.right
            while node:
                self.stack.append(node)
                node = node.left

        return node_to_return


from helperfunc import build_tree_breadth_first

root = build_tree_breadth_first(sequence=[6, 2, 8, 1, 3, 7, 9])
# Example of iterate a tree:
iterator = BSTIterator(root)
while iterator.hasNext():
    node = iterator.next()
    print(node.val)
        return rslt

    def dfs_traverse(self, node, rslt, target):
        if node is None:
            return
        self.dfs_select_path(node, rslt, [], target)

        self.dfs_traverse(root.left, rslt, target)
        self.dfs_traverse(root.right, rslt, target)

    def dfs_select_path(self, node, rslt, curr_path, target):
        if node is None:
            return
        curr_path.append(node.val)
        if node.val == target:
            rslt.append(curr_path[:])

        self.dfs_select_path(node.left, rslt, curr_path, target - node.val)
        self.dfs_select_path(node.right, rslt, curr_path, target - node.val)
        curr_path.pop()


from helperfunc import build_tree_breadth_first, TreeNode

sol = Solution2()
root = build_tree_breadth_first([1, 2, 3, 4, None, 2])
assert sol.binaryTreePathSum2(root, 6) == [[1, 3, 2], [2, 4]]
root = build_tree_breadth_first([1, -2, None, 1])
root.left.left.left = TreeNode(2)
assert sol.binaryTreePathSum2(root, 2) == [[1, -2, 1, 2], [2]]
示例#12
0
        self.left, self.right = None, None
"""


class Solution:
    """
    @param root: A Tree
    @return: Preorder in ArrayList which contains node values.
    """
    def preorderTraversal(self, root):
        # write your code here
        if root is None:
            return []
        stack = [root]
        rslt = []
        while stack:
            node = stack.pop()
            rslt.append(node.val)
            if node.right:
                stack.append(node.right)
            if node.left:
                stack.append(node.left)
        return rslt


from helperfunc import build_tree_breadth_first

sol = Solution()
root = build_tree_breadth_first(sequence=[1, 2, 3, 4, 5, 6, 7])
sol.preorderTraversal(root=root)
        # use a max_heap to store the max_distance
        max_heap = []
        while stack:
            node = stack.pop()
            heapq.heappush(max_heap, (-1 * abs(node.val - target), node.val))
            if len(max_heap) > k:
                heapq.heappop(max_heap)
            # print(node.val)
            if node.right:
                node = node.right
                while node:
                    stack.append(node)
                    node = node.left

        rslt = []
        for _, val in reversed(max_heap):
            rslt.append(val)

        return rslt


from helperfunc import TreeNode, build_tree_breadth_first

root = build_tree_breadth_first([6, 2, 8, 1, 3, 7, 9])
sol = Solution()
sol.closestKValues(root=root, target=10, k=2)

root = build_tree_breadth_first(sequence=[3, 1, 4, None, 2])
sol = Solution()
sol.closestKValues(root, 0.275, 2)