def TEST(arr):
    root = TreeNode.grow(arr)
    root.pprint()
    root_iter = flatten(root)
    while root_iter:
        print(root_iter.val, end='\t')
        root_iter = root_iter.right
Example #2
0
def lowestCommonAncestorCircuitBreak(root, p, q):
    if not root: return None

    def lca(root, p, q):
        ret = (None, None)
        if not root: return ret

        ret = (root if p == root.val else None,
               root if q == root.val else None)
        if ret[0] and ret[1]: return ret

        for node in [root.left, root.right]:
            rp, rq = lca(node, p, q)
            if rp: ret = (rp, ret[1])
            if rq: ret = (ret[0], rq)

            if ret[0] and ret[1]:
                if ret[0] != ret[1]:
                    return (root, root)
                return ret

        return ret

    rp, rq = lca(root, p, q)
    if rp != rq: return None
    return rp


root = TreeNode.grow([3, 5, 1, 6, 2, 0, 8, None, None, 7, 4])
print(lowestCommonAncestor(root, 5, 1).val)
def averageOfLevel(root):
    avgs = []
    if not root: return avgs

    queue = [root]
    while queue:
        next_queue = []
        avg = 0.0
        cnts = 0
        for node in queue:
            if node.left:
                next_queue.append(node.left)
            if node.right:
                next_queue.append(node.right)
            avg += node.val
            cnts += 1
        avg = avg / cnts
        avgs.append(avg)
        del queue
        queue = next_queue

    return avgs


def TEST(root):
    print(averageOfLevel(root))

root = TreeNode.grow([3, 9, 20, None, None, 15, 7])
TEST(root)
''' Diamerter of a binary tree
'''

from lib_arbortem import TreeNode


def diameterOfBinaryTree(root):
    if not root: return 0

    def dfs(root):
        # Return: max depth and max route through @root
        if not root: return 0, 0
        depth_l, max_route_l = dfs(root.left)
        depth_r, max_route_r = dfs(root.right)
        depth = 1 + max(depth_l, depth_r)
        max_route = max(max_route_l, max_route_r)
        max_route = max(max_route, depth_l + depth_r)
        return depth, max_route

    _, max_route = dfs(root)
    return max_route


root = TreeNode.grow([1, 2, 3, 4, 5])
print(diameterOfBinaryTree(root))
def TEST(tree_list):
    root = TreeNode.grow(tree_list)
    #root.pprint()
    print(widthOfBinaryTree(root))
""" Binary tree tilt
"""

from lib_arbortem import TreeNode


def findTilt(root):
    if not root: return 0

    def find_tuple(root):
        if not root:
            return 0, 0
        sum_left, tilt_left = find_tuple(root.left)
        sum_right, tilt_right = find_tuple(root.right)
        sum_root = root.val + sum_left + sum_right
        tilt_root = abs(sum_left - sum_right) + tilt_left + tilt_right
        return sum_root, tilt_root

    _, tilt = find_tuple(root)
    return tilt


root = TreeNode.grow([1, 2, 3])
root.pprint()
print(findTilt(root))
    if not root: return None

    def convert(root, suff_val):
        """ Return min node and its converted value
        """
        _update = True
        if root.right:
            min_val, suff_val = convert(root.right, suff_val)
            if min_val == root.val:
                root.val = suff_val
                _update = False

        if _update:
            min_val = root.val
            suff_val += root.val
            root.val = suff_val

        if root.left:
            min_val, suff_val = convert(root.left, suff_val)

        return min_val, suff_val

    convert(root, 0)
    return root


root = TreeNode.grow([5, 2, 13])
root.pprint()
convertBST(root)
root.pprint()
        
        node, size = search(root.left, k)
        tot_size = size
        res = node
            
        # 1-based indexing
        if tot_size == k - 1:
            res = root
        tot_size += 1

        node, size = search(root.right, k - tot_size)
        tot_size += size
        if not res:
            res = node
                    
        return res, tot_size

    res, _ = search(root, k)
    assert res
    return res.val



root = TreeNode.grow([3, 1, 4, None, 2])
root.pprint()

    
print(kthSmallest(root, 2))
print(kthSmallest(root, 0))
print(kthSmallest(root, 3))
def TEST(node_list):
    root = TreeNode.grow(node_list)
    ref = find_ref(root)
    tgt = findSecondMinimumValue(root)
    assert ref == tgt, ('ref', ref, '!=', tgt)

def findTargetFlatten(root, k):
    if root is None: return False

    def flatten(root, sorted_buf):
        if root is None: return
        flatten(root.left, sorted_buf)
        sorted_buf.append(root.val)
        flatten(root.right, sorted_buf)

    arr = []
    flatten(root, arr)
    i = 0
    j = len(arr) - 1
    while i < j:
        curr = arr[i] + arr[j]
        if curr == k:
            return True
        if curr < k:
            i += 1
        else:
            j -= 1

    return False


root = TreeNode.grow([5, 3, 6, 2, 4, None, 7])
print(findTarget(root, 9))
print(findTarget(root, 28))
Example #11
0
""" sum root-to-leaf numbers
"""

from lib_arbortem import TreeNode


def sumNumbers(root):
    def kern(root, prefix=0):
        if not root: return 0
        val = 10 * prefix + root.val
        if not root.left and not root.right:
            return val
        left_sum = kern(root.left, val)
        right_sum = kern(root.right, val)
        return left_sum + right_sum

    return kern(root)


def TEST(root, tgt):
    root.pprint()
    val = sumNumbers(root)
    if val != tgt:
        print('Error', val, 'but expect', tgt)
    else:
        print('Ok')


TEST(TreeNode.grow([1, 2, 3]), 25)
""" Merge Twi Binary Trees
"""

from lib_arbortem import TreeNode

def mergeTrees(t1, t2):
    def merge(t1, t2):
        if not t1: return t2
        if not t2: return t1
        root = TreeNode(t1.val + t2.val)
        root.left = merge(t1.left, t2.left)
        root.right = merge(t1.right, t2.right)
        return root

    return merge(t1, t2)



t1 = TreeNode.grow([1,3,2,5])
t2 = TreeNode.grow([2,1,3,None,4,None,7])
t = mergeTrees(t1, t2)
Example #13
0
def addOneRow(root, v, d):
    def attach(node, v, is_left=False):
        new_node = TreeNode(v)
        if is_left:
            new_node.left = node
        else:
            new_node.right = node
        return new_node

    def search(root, depth):
        if depth > d or root is None:
            return root
        if depth + 1 != d:
            search(root.left, depth + 1)
            search(root.right, depth + 1)
        else:
            root.left = attach(root.left, v, is_left=True)
            root.right = attach(root.right, v, is_left=False)
        return root

    if 1 == d:
        new_root = TreeNode(v)
        new_root.left = root
        return new_root
    else:
        return search(root, 1)


root = addOneRow(TreeNode.grow([4, 2, 6, 3, 1, 5]), 1, 1)
root.pprint()
def flatten(root):
    if not root: return

    def flatten_kern(root, head=None):
        if not root: return head
        head = flatten_kern(root.right, head)
        head = flatten_kern(root.left, head)
        root.left = None
        root.right = head
        return root

    head = flatten_kern(root, None)
    return head


def TEST(arr):
    root = TreeNode.grow(arr)
    root.pprint()
    root_iter = flatten(root)
    while root_iter:
        print(root_iter.val, end='\t')
        root_iter = root_iter.right


root = TreeNode.grow([1, 2, None, 3, 5])
flattenMorris(root)
while root:
    print(root.val, end='\t')
    root = root.right
def TEST(nodes):
    root = TreeNode.grow(nodes)
    print([n.val for n in get_boundary(root)])
Example #16
0
""" Binary tree string repr
"""

from lib_arbortem import TreeNode


def tree2str(t):
    def tree_repr(t):
        if not t: return ""
        if not t.left:
            s0 = "()" if t.right else ""
        else:
            s0 = "(" + tree_repr(t.left) + ")"
        s1 = "" if not t.right else ("(" + tree_repr(t.right) + ")")
        return str(t.val) + s0 + s1

    return tree_repr(t)


t = TreeNode.grow([1, 2, 3, 4])
print(tree2str(t))

t = TreeNode.grow([1, 2, 3, None, 4])
print(tree2str(t))