Data Structure and Algorithm 4 | Walking and Searching

0_QXrDY4nVmhZ1umbX

1. Walking Algorithms

(1) Array Walking

Time complexity .

(2) 2D Array (Matrix) Walking

Time complexity .

(3) Linked List Walking

Time complexity .

(4) Pre-Order Tree Walking (DFS)

Suppose we have a tree of,

Then the pre-order output should be a sequence of,

Time complexity ,

(6) In-Order Tree Walking (DFS)

See leetcode 94.

Suppose we have a tree of,

Then the in-order output should be a sequence of,

Time complexity ,

(7) Post-Order Tree Walking (DFS)

Suppose we have a tree of,

Then the post-order output should be a sequence of,

Time complexity ,

(8) Walking DAG (DFS)

Directed acyclic graph are the simplest graph that we can walk through without cycles.

Time complexity .

(9) Walking Graphs with Cycles (DFS)

We should maintain a visited set to record the nodes we have visited and this requires an space complexity.

Time complexity .

Note that the visited can also be a list but searching a list has a higher time complexity than a set. Remember this algorithm works because we are passing the pointer to visited as an argument so that if we make a copy of the set or list we pass, the algorithm will no longer work for us.

2. Searching

(1) Searching Sorted Array: Binary Search (Iterations)

Time complexity .

(2) Searching Sorted Array: Binary Search (Recursion)

Time complexity .

(3) Searching Hash Table

Time complexity at the best case is , and at the worst case is .

(4) Search String Trie

String trie is a more efficient data structure for word searching. Suppose the trie nodes has,

And we use the add function to add a new word to trie.

Then, the following search algorithm (similar to walk through a graph) has a time complexity of for searching a word in that data structure,