You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
If n is not the root of T, its level is 1 greater than the Level of its parent
Height
Height of a tree T defined in terms of the levels of its nodes
If T is empty, its height is not defined
If T is not empty, its height is equal to the maximum level of its nodes
Binary Tree
A binary tree is (recursive definition)
An empty tree, or
A node with a right binary tree and a left binary tree (called left/right subtrees)
The maximum number of children for all nodes in a binary tree: ?????
Tree Traversal
A Tree Data Structure can be traversed in following ways:
Depth First Search (DFS)
Preorder Traversal
Inorder Traversal
Postorder Traversal
Level Order Traversal or Breadth First Search (BFS)
DFS
Pre-order Traversal
Pseudo-code
Algorithm Preorder(tree)
1. Visit the root.
2. Traverse the left subtree, i.e., call Preorder(left->subtree)
3. Traverse the right subtree, i.e., call Preorder(right->subtree)
Algorithm Inorder(tree)
1. Traverse the left subtree, i.e., call Inorder(left->subtree)
2. Visit the root.
3. Traverse the right subtree, i.e., call Inorder(right->subtree)
Algorithm Inorder(tree)
1. Traverse the left subtree, i.e., call Inorder(left->subtree)
2. Traverse the right subtree, i.e., call Inorder(right->subtree)
3. Visit the root.
classSolution(object):
deflevelOrder(self, root):
""" :type root: TreeNode :rtype: List[List[int]] -> [[3],[9,20],[15,7]] """result= []
ifroot:
bfs_queue= [[root]]
whilelen(bfs_queue) >0:
cur_level=bfs_queue.pop(0) # dequeresult.append([node.valfornodeincur_level])
next_level= []
# add all the children of the node in the cur level in the queuefornodeincur_level:
ifnode.left:
next_level.append(node.left)
ifnode.right:
next_level.append(node.right)
bfs_queue.append(next_level)
iflen(next_level) ==0:
breakreturnresult
Binary Search Tree
A binary search tree is a binary tree with the following property at all nodes:
Every key in the left subtree is smaller than itself
Every key in the right subtree is larger than itself
In-order traversal of binary search trees are sorted lists
Binary Search helps us reduce the search time from linear $O(n)$ to logarithmic $O(log(n))$.
defbinary_search(array) ->int:
left, right=min(search_space), max(search_space) # could be [0, n], [1, n] etc. Depends on problemwhileleft<right:
mid=left+ (right-left) //2# determine the mid pointifcondition(mid):
right=midelse:
left=mid+1returnleft