from geeksforgeeks.datastructure.binary_tree.binary_tree import Node, array_to_tree def print_path(node, parent): stack = [] while node: stack.append(str(node.val)) node = parent[node] print('->'.join(reversed(stack))) def paths(root): if not root: return stack = [root] parent = {root: None} while stack: node = stack.pop() if not node.left and not node.right: print_path(node, parent) continue if node.right: parent[node.right] = node stack.append(node.right) if node.left: parent[node.left] = node stack.append(node.left) paths(array_to_tree([6, 3, 5, 2, 5, None, 4, None, None, 7, 4]))
from geeksforgeeks.datastructure.binary_tree.binary_tree import array_to_tree def all_leaves(node): if node: all_leaves(node.left) if not node.left and not node.right: print(node.val, end=' ') all_leaves(node.right) all_leaves(array_to_tree([1, 2, 3, 4, None, 5, 8, None, None, None, None, 6, 7, 9, 10]))
from geeksforgeeks.datastructure.binary_tree.binary_tree import array_to_tree def k_distance(root, k): if not root: return if k == 0: print(root.val) else: k_distance(root.left, k - 1) k_distance(root.right, k - 1) k_distance(array_to_tree([1, 2, 3, 4, 5, 8]), 2)
from geeksforgeeks.datastructure.binary_tree.binary_tree import Node, array_to_tree def sum_of_parent_of_x(root, x): s = [0] helper(root, s, x) return s[0] def helper(node, s, x): if not node: return if (node.left and node.left.val == x) or (node.right and node.right.val == x): s[0] += node.val helper(node.left, s, x) helper(node.right, s, x) tree = array_to_tree([4, 2, 5, 7, 2, 2, 3]) print(sum_of_parent_of_x(tree, 2))
from geeksforgeeks.datastructure.binary_tree.binary_tree import Node, array_to_tree def print_path(root, x): arr = [] if has_path(root, arr, x): print(' -> '.join(list(map(str, arr)))) def has_path(node, arr, x): if not node: return False arr.append(node.val) if node.val == x: return True if has_path(node.left, arr, x) or has_path(node.right, arr, x): return True arr.pop() return False tree = array_to_tree([1, 2, 3, 4, 5, 6, 7]) print_path(tree, 5)
from geeksforgeeks.datastructure.binary_tree.binary_tree import Node, array_to_tree def solution(root, low, high): if not root: return level = 1 marker = Node(None) queue = [root, marker] while queue: node = queue.pop(0) if node == marker: if level >= low: print() level += 1 if not queue or level > high: break queue.append(marker) continue if level >= low: print(node.val, end=' ') if node.left: queue.append(node.left) if node.right: queue.append(node.right) solution(array_to_tree([20, 8, 22, 4, 12, None, None, None, None, 10, 14]), 2, 3)
from geeksforgeeks.datastructure.binary_tree.binary_tree import Node, array_to_tree def routes(stack, node): if not node: return stack.append(node.val) if not node.left and not node.right: print(stack) routes(stack, node.left) routes(stack, node.right) stack.pop() routes([], array_to_tree([1, 2, 3, 4, 5]))