Binary tree
Binary tree
A Binary Tree is a hierarchical data structure where each node has at most two children (left
and right). Many problems that involve hierarchical relationships, recursive structures, or
order-based traversals can be solved using Binary Trees.
4️⃣ Example 1: Tree Traversal (Preorder, Inorder, Postorder, Level Order BFS)
Problem Statement:
Given a binary tree, print the Preorder, Inorder, Postorder, and Level Order traversals.
# Preorder Traversal
def preorder(root):
return [root.val] + preorder(root.left) + preorder(root.right) if root
else []
# Inorder Traversal
def inorder(root):
return inorder(root.left) + [root.val] + inorder(root.right) if root
else []
# Postorder Traversal
def postorder(root):
return postorder(root.left) + postorder(root.right) + [root.val] if root
else []
Given a binary tree, find the Lowest Common Ancestor (LCA) of two nodes.
Identification:
left = lowest_common_ancestor(root.left, p, q)
right = lowest_common_ancestor(root.right, p, q)
Identification:
mid = len(nums) // 2
root = TreeNode(nums[mid])
root.left = sorted_array_to_bst(nums[:mid])
root.right = sorted_array_to_bst(nums[mid+1:])
return root