global diameter # Update diameter, when curr_diameter > left + right depth diameter = max(diameter, left_depth + right_depth) # Notice return max(left_depth, right_depth) + 1 # maximum_depth def diameter_of_binary_tree(root: BinaryTreeNode) -> int: find_depth( root ) # basically find the diameter when we are processing the tree for finding depth return diameter if __name__ == "__main__": tree_input = input_array() tree_root = BinaryTree.single_line_input(tree_input) BinaryTree.display(tree_root) print("diameter : ", diameter_of_binary_tree(tree_root)) """ 1 / \ 2 3 / \ 4 5 1 2 3 4 5 -1 -1 -1 -1 -1 -1 """ """ 0 / \ 1 2
finding_x_for_each_node__pre_order(root.left, x_table, horizontal_distance - 1) finding_x_for_each_node__pre_order(root.right, x_table, horizontal_distance + 1) def vertical_order(root): x_table: Dict[int, list] = dict() # map of number, list finding_x_for_each_node__pre_order(root, x_table) for x in sorted(x_table.keys()): print_array_inline(x_table[x]) if __name__ == "__main__": tree_root = BinaryTree.single_line_input(input_array()) BinaryTree.display(tree_root) vertical_order(tree_root) """ 1 / \ 2 3 / \ \ 4 5 6 / \ 7 8 1 2 3 4 5 -1 6 7 -1 -1 8 -1 -1 -1 -1 -1 -1 Output 7 4
def find_height(root): if root is None: return 0 # height of the leaf node will be considered 0, in the WAY-1 of implementation we consider None's height 0 # if we comment this if condition, will get height according to WAY-2 if root.left is None and root.right is None: return 0 left_height = find_height(root.left) right_height = find_height(root.right) return max(left_height, right_height) + 1 if __name__ == "__main__": tree_root = BinaryTree.single_line_input(input_array()) print(find_height(tree_root)) pass """ Height of a tree can be defined in no of ways 2 popular ways are WAY 1 with this we assume a tree with null (None), root will have a height of 0 10 --> 1 20 30 40 --> 2 40 50 --> 3 WAY 2