def update_tree(): tree = TreeNode(10) tree.left = TreeNode(12) tree.right = TreeNode(15) tree.left.left = TreeNode(25) tree.left.left.right = TreeNode(100) tree.left.right = TreeNode(30) tree.right.left = TreeNode(36) return tree
def build_tree(preorder, inorder): """ :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode """ length = len(preorder) if length == 0: return None node = TreeNode(preorder[0]) temp = inorder.index(preorder[0]) node.left = build_tree(preorder[1:temp + 1], inorder[0:temp]) node.right = build_tree(preorder[temp + 1:], inorder[temp + 1:]) return node
def insert(self, key): """ Insert new key into node """ # Create new node n = TreeNode(key) if not self.node: self.node = n self.node.left = AvlTree() self.node.right = AvlTree() elif key < self.node.val: self.node.left.insert(key) elif key > self.node.val: self.node.right.insert(key) self.re_balance()
level = [] while queue: node = queue.pop(0) if node.left is not None: level.append(node.left) if node.right is not None: level.append(node.right) queue = level return height def print_tree(root): if root is not None: print(root.val) print_tree(root.left) print_tree(root.right) if __name__ == '__main__': tree = TreeNode(10) tree.left = TreeNode(12) tree.right = TreeNode(15) tree.left.left = TreeNode(25) tree.left.left.right = TreeNode(100) tree.left.right = TreeNode(30) tree.right.left = TreeNode(36) height = max_height(tree) print_tree(tree) print("height:", height)
for node in level: if node.left is None and node.right is None: return height if node.left is not None: new_level.append(node.left) if node.right is not None: new_level.append(node.right) level = new_level return height def print_tree(root): if root is not None: print(root.val) print_tree(root.left) print_tree(root.right) if __name__ == '__main__': tree = TreeNode(10) tree.left = TreeNode(12) tree.right = TreeNode(15) tree.left.left = TreeNode(25) tree.left.left.right = TreeNode(100) tree.left.right = TreeNode(30) tree.right.left = TreeNode(36) height = min_height(tree) print_tree(tree) print("height:", height)
class DeepestLeft: def __init__(self): self.depth = 0 self.Node = None def find_deepest_left(root, is_left, depth, res): if not root: return if is_left and depth > res.depth: res.depth = depth res.Node = root find_deepest_left(root.left, True, depth + 1, res) find_deepest_left(root.right, False, depth + 1, res) if __name__ == "__main__": root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(3) root.left.left = TreeNode(4) root.left.right = TreeNode(5) root.right.right = TreeNode(6) root.right.right.right = TreeNode(7) res = DeepestLeft() find_deepest_left(root, True, 1, res) if res.Node: print(res.Node.val)