Binary Tree
from __future__ import annotations
class Node:
"""
A Node has data variable and pointers to Nodes to its left and right.
"""
def __init__(self, data: int) -> None:
self.data = data
self.left: Node | None = None
self.right: Node | None = None
def display(tree: Node | None) -> None: # In Order traversal of the tree
"""
>>> root = Node(1)
>>> root.left = Node(0)
>>> root.right = Node(2)
>>> display(root)
0
1
2
>>> display(root.right)
2
"""
if tree:
display(tree.left)
print(tree.data)
display(tree.right)
def depth_of_tree(tree: Node | None) -> int:
"""
Recursive function that returns the depth of a binary tree.
>>> root = Node(0)
>>> depth_of_tree(root)
1
>>> root.left = Node(0)
>>> depth_of_tree(root)
2
>>> root.right = Node(0)
>>> depth_of_tree(root)
2
>>> root.left.right = Node(0)
>>> depth_of_tree(root)
3
>>> depth_of_tree(root.left)
2
"""
return 1 + max(depth_of_tree(tree.left), depth_of_tree(tree.right)) if tree else 0
def is_full_binary_tree(tree: Node) -> bool:
"""
Returns True if this is a full binary tree
>>> root = Node(0)
>>> is_full_binary_tree(root)
True
>>> root.left = Node(0)
>>> is_full_binary_tree(root)
False
>>> root.right = Node(0)
>>> is_full_binary_tree(root)
True
>>> root.left.left = Node(0)
>>> is_full_binary_tree(root)
False
>>> root.right.right = Node(0)
>>> is_full_binary_tree(root)
False
"""
if not tree:
return True
if tree.left and tree.right:
return is_full_binary_tree(tree.left) and is_full_binary_tree(tree.right)
else:
return not tree.left and not tree.right
def main() -> None: # Main function for testing.
tree = Node(1)
tree.left = Node(2)
tree.right = Node(3)
tree.left.left = Node(4)
tree.left.right = Node(5)
tree.left.right.left = Node(6)
tree.right.left = Node(7)
tree.right.left.left = Node(8)
tree.right.left.left.right = Node(9)
print(is_full_binary_tree(tree))
print(depth_of_tree(tree))
print("Tree is: ")
display(tree)
if __name__ == "__main__":
main()Binary Trees
Explain and implement a Binary Tree.
A tree is a collection of nodes and edges between them.
It cannot have any cycles, which are edges that form a loop between nodes.
We also only consider rooted trees in computer science, which is a tree that has one root node that is able to access all other nodes.
For a tree to be a binary tree, each node can have a maximum of two children.
It's important to be able to identify and explain tree terminology as well. If given a tree, be able to point out each component.
root: The single node of a tree that can access every other node through edges.
parent node: A node that is connected to lower nodes in the tree. If a tree only has one node, it is not a parent node because there are no children.
child node: A node that is connected to a higher node in the tree. Every node except for the root is a child node of some parent.
sibling nodes: Nodes that have the same parent.
leaf node: A node that has no children (at the ends of the branches of the tree)
internal node: A non-leaf node (aka a parent)
path: A series of nodes that can be traveled through edges.
subtree: A smaller portion of the original tree. Any node that is not the root node is itself the root of a subtree.
Know the basics of each term
A non-empty tree has to have a root.
A tree doesn't have any parent nodes if there are no children.
What's the min/max number of parent and leaf nodes for a tree with 5 nodes?
Implementing as a balanced tree results in min number of parents and max number of leaves: 2 parents, 3 leaves
All that we need in order to implement a binary tree is a TreeNode class that can store a value and references to a left and right child. We can create a tree by assigning the left and right properties to point to other TreeNode instances:
Identify the three types of tree traversals: pre-order, in-order, and post-order.
Pre-order: Values are accessed as soon as the node is reached.
In-order: Values are accessed after we have fully explored the left but before we explore the right branch.
Post-order: Values are accessed after all of our children have been accessed.
*Breadth First: The previous three are types of Depth First Traversals. Breadth first accesses values of nodes by level, left to right, top to bottom.
Explain and implement a Binary Search Tree.
A binary search tree is a binary tree with the added stipulation that all values to the left of a node are less than its value and all values to the right are greater than its value.
Example of a BST with an insert method. You won't be asked to implement a removal:
Balanced Binary Tree
Balanced Binary Tree
Given a binary tree class that looks like this:
write a function that checks to see if a given binary tree is perfectly balanced, meaning all leaf nodes are located at the same depth. Your function should return true if the tree is perfectly balanced and false otherwise.
Analyze the time and space complexity of your function.
JS Solution:
Binary Search Tree from Sorted Array
Given an array that is sorted in ascending order containing unique integer elements, write a function that receives the sorted array as input and creates a valid binary search tree with minimal height.
For example, given an array [1, 2, 3, 4, 5, 6, 7], your function should return a binary search tree with the form
Note that when we say "binary search tree" in this case, we're just talking about a tree that exhibits the expected form of a binary search tree. The tree in this case won't have an insert method that does the work of receiving a value and then inserting it in a valid spot in the binary search tree. Your function should place the values in valid spots that adhere to the rules of binary search trees, while also seeking to minimize the overall height of the tree.
Here's a BinaryTreeNode class that you can use to construct a binary search tree:
Analyze the time and space complexity of your solution.
Create a Minimal Height BST from Sorted Array
Understanding the Problem
This problem asks us to create a valid binary search tree from a sorted array of integers. More specifically, the resulting binary search tree needs to be of minimal height. Our function should return the root node of the created binary search tree.
From the given example where the input is [1, 2, 3, 4, 5, 6, 7], the expected answer is a binary search tree of height 3. This is the minimal height that can be achieved for an array of 7 seven elements. Try as we might, there's no way to construct a binary search tree containing all of these elements that has a shorter height.
Coming Up with a First Pass
A straightforward way to do this would be to take the first element of our array, call that the root, and then iterate through the rest of our array, adding those elements as nodes in the binary search tree. In pseudocode, that might look something like this:
Another BST Implementation:
Last updated
Was this helpful?


