Tree is a basic data structure. The most popular tree is the binary tree, which has a left child and a right child. The exercise usually gives you the root node of the tree. The basic method to solve a tree problem is recursive.
Traverse the tree
Iteration
1 2 3 4 5 6
openlist = [root] whilelen(openlist) > 0: node = openlist.pop() # openlist.pop(0) if you want BFS check(node) openlist.append(node.left) openlist.append(node.right)
Recursive
1 2 3 4
defcheck_tree(node): if node: check_tree(node.left) check_tree(node.right)
The above two ara both DFS(Deep First Search), in order to achieve the BFS(Breadth First Search), in other means, traverse the tree layer by layer, we need to use a dictionary to store the node
1 2 3 4 5 6 7 8 9 10
dic_tree = {}
defcheck_tree_breadth(node, depth=1): if node: if depth notin dic_tree: dic_tree[depth] = [node.val] else: dic_tree[depth].append(node.val) check_tree_breadth(node.left, depth+1) check_tree_breadth(node.right, depth+1)
Fenwick tree is also called Binary Indexed Tree. This kind of data structure can do the calculation of sum from 0 to ith of a list very efficiently.
It can also be used to calculate the frequency. Below is a code used to calculate the number of values from 0 to i.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classfenwickTree: def__init__(n): self.array = [0] * n
defadd(i): while i < len(self.array): self.array[i] += 1 i += i & -i
defquery(i): ans = 0 while i >= 0: ans += self.array[i] i -= i & -i return ans
Relevant application is in Leetcode No.315.
Heap
Heap is a useful data structure which can store the elements in order. In Python, there is a built in heap library called Heapq.
No.253 - Meeting Room
Make the start time of meeting in order
Use heap to store the end time of each meeting
When the meeting with earliest end time is smaller than the coming meeting with earliest start time, pop that meeting, otherwise not. Then heappush the new end time of the new coming meeting.
Divide the problem into a number of subproblems that are smaller instances of the same problem.
Conquer the subproblems by solving them recursively. If the subproblem sizes are small enough, however, just solve the subproblems in a straightforward manner.
Combine the solutions to the subproblems into the solution for the original problem.
Samples and exercise
Binary search
Decrease the time from $O(n)$ to $O(log(n))$
No.4 Median of Two Sorted Arrays This exercise need we use binary search to find the proper value.
Majority elements
If an element is the majority element(appears more than n/2 times), it should be the majority element in the left half sequence or in the right sequence, otherwise it cannot be the majority element.
Quick sort
Binary sort.
Merge sort
Merge two in-order sequence to a whole sequence. The best time is $O(nlog(n))$