Exemplo n.º 1
0
def kth_node_in_BST(root, k):
    """
    :param root: Binary Search Tree root
    :param k: kth smallest
    :return: kth smallest node
    """
    def recursion(root, k):
        nonlocal target
        if not root:
            return k
        k = recursion(root.left, k)
        if not target:
            if k == 1:
                target = root
            else:
                k -= 1
        if not target:
            k = recursion(root.right, k)
        return k

    target = None
    recursion(root, k)
    return target


from datstru import list_to_treenode
tree = list_to_treenode([8, 6, 10, 5, 7, 9, 11])
k = 1
ans = kth_node_in_BST(tree, k)
print()
Exemplo n.º 2
0
1
3 2
4 5 6 7
15 14 13 12 11 10 9 8
"""


def print_tree_lines(root):
    """
    :param root: tree root
    :return: None
    """
    layer = [root]
    next_layer = []
    reverse = -1
    while layer:
        for node in layer[::-1]:
            if node:
                print(node.val, end=" ")
                next_layer.extend([node.left, node.right][::-reverse])
        print()
        layer = next_layer
        next_layer = []
        reverse = -reverse
    return


from datstru import list_to_treenode

root = list_to_treenode(list(range(1, 32)))
print_tree_lines(root)
Exemplo n.º 3
0
面试题55:二叉树的深度
题目1:二叉树的深度
输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点一次经过的节点
形成树的一条路径,从最长路径的长度为树的深度。

例:
        1
       / \
      2   3
     / \   \
    4   5   6
       /
      7
深度为4。
"""


def depth_of_tree(root):
    """
    :param root: tree root
    :return: height of tree
    """
    if not root:
        return 0
    left = depth_of_tree(root.left)
    right = depth_of_tree(root.right)
    return max(left, right) + 1

from datstru import list_to_treenode
tree = list_to_treenode([1,2,3,4,5,'null',6,'null','null',7])
print(depth_of_tree(tree))
Exemplo n.º 4
0
        return seq

    seq = []
    preorder(root)
    return seq


def deserialize(sequence):
    """
    :param sequence:pre-order val list
    :return: tree root
    """
    def rebuild(seqence, i):
        val = seqence[i]
        if val == '$':
            return None
        root = TreeNode(val)
        root.left = rebuild(seqence, i + 1)
        root.right = rebuild(seqence, i + 2)
        return root

    if not sequence:
        return None
    return rebuild(sequence, 0)


root = list_to_treenode([1, 2, 3, 4, 'null', 5, 6])
seq = serialize(root)
tree = deserialize(seq)
print(seq)