Sure interview datastructure-1103

2,254 views

Published on

0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
2,254
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
93
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Sure interview datastructure-1103

  1. 1. SureInterview PREPARATION ON DATA STRUCTURE http://www.sureinterview.com Mar 6, 2011 The latest version can be found at http://code.google.com/p/sureinterview/downloads
  2. 2. Data Structure SearchHow to implement your own HashSet by using ArrayListHow to implement your own HashSet by using ArrayListsubmit my answer SearchImplement LRU cache algorithmImplement the LRU cache algorithm. Given following interface. 1 interface CacheStrategy<K, T> { ? 2 /** 3 * get the data by key from cache. 4 * 5 * @param key 6 * @return 7 */ 8 T get(K key); 9 10 /** 11 * put <key, data> pair to cache 12 * 13 * @param key 14 * @param data 15 */ 16 void put(K key, T data); 17 }The get and put can be done in O(n) time.1 the data structureThe core of this algorithm is a double linked list that indexed by a hash map. The double link is implicitly sorted by the age ofthe data. Once the data is accessed, it is considered to be refreshed and thus moved to the head of the double linkedlist(age==0). 1 class Node { ? 2 Node prev; //double link 3 Node next; 4 T data; //data and key 5 K key; 6 } 7 Map<K, Node> map; //node is indexed the key to support node access in O(1).2 double linked listFor a double link, the insert and deletion only takes O(1). So, it is quite efficient to implement the LRU structure. The reason touse double linked list rather than the single linked one is to delete the note from the middle part.By define the head and tail node, the insertion and deletion of a node can be simplified.Initialize the head nodes. 1 //hook up the head and tail nodes ? 2 head = new Node(null, null); 3 tail = new Node(null, null); 4 head.next = tail; 5 tail.prev = head;Remove the note from the list. 1 private void detach(Node node) { ? 2 // detach it from the queue 3 node.prev.next = node.next; 4 node.next.prev = node.prev; 5 }Attach the node after head.
  3. 3. 1 private void attach(Node head, Node node) { ? 2 // add note behind the head. 3 node.prev = head; 4 node.next = head.next; 5 node.next.prev = node; 6 node.prev.next = node; 7 }3 maintain the cacheGet the data from the cache needs to move the node from middle to the head. 1 @Override ? 2 public T get(K key) { 3 Node node = map.get(key); 4 if (node == null) 5 return null; 6 7 if (map.size() == 1) 8 return node.data; 9 10 // refresh 11 // - detach it from the queue 12 detach(node); 13 // - attach it to head 14 attach(head, node); 15 return node.data; 16 }Besides a fresh, putting data into the cache also needs to maintain the size and content of the cache. 1 /** ? 2 * put <key,data> into cache. 3 */ 4 @Override 5 public void put(K key, T data) { 6 if (maxsize <= 0) 7 return; 8 9 Node node = map.get(key); 10 if (node != null) { 11 // hit, just update data 12 detach(node); 13 attach(head, node); 14 node.data = data; 15 } else { 16 // miss, create new data 17 node = new Node(key, data); 18 map.put(key, node); 19 attach(head, node); 20 if (map.size() > maxsize) { 21 // overflow, remove the tail 22 detach(tail.prev); 23 map.remove(tail.prev.key); 24 } 25 } 26 }CodeCode can be found at: http://code.google.com/p/sureinterview/source/browse/src/solution/misc/CacheStrategies.java#47 Searchimplement a queue with stack(s)implement a queue with stack(s)submit my answer SearchDesign a class that supports insert, delete, and get random element.Given a collection of integer, design a class that supports: 1. add(data) - insert an element 2. delete(data) - delete an element 3. getRandom(data) - return a random elementGeneral IdeaThe commonly used data structures do not efficiently satisfy all of the features. So we should hook up multiple data structuresto provide an efficient solution.Because the getRandom is most demanding -- only array can support getRandom(), the array should be used to let getRandompart work. The array is not quite good at deleting data in the middle, so the data should be stored in some other data
  4. 4. structure. Here, the link list wont work either because the delete function needs to randomly access the data. A betterstructure is the hash table. So, we can use a hash table to save the data and an array to provide random access function.implementationwhen all data elements are uniqueHere is the pseudo code. Note that this version does not support duplicated data. 1 class AClassSupportsGetRandom<T> { ? 2 class Data { 3 T data; 4 int idx; 5 } 6 7 Data dataArr[]; // for hashing data 8 final int HASH_SIZE = 0x100000 - 1; 9 10 int rndArr[]; // the array for getting random data. 11 int size;; 12 13 void add(T data) { 14 int pos = hashFunction(data); // get the insert position 15 dataArr[pos].data = data; 16 dataArr[pos].idx = size; // append to the tail of the index array. hook two structures together. 17 18 rndArr[size] = pos; 19 size++; 20 } 21 22 public int getSize() { 23 return size; 24 } 25 26 private final int hashFunction(T data) { 27 int pos = Math.abs(data.hashCode()) % HASH_SIZE; 28 // handle conflict, size, etc. 29 return pos; 30 } 31 32 T getRandomData() { 33 int rnd = getAValidRandomNumber(); 34 return dataArr[rndArr[rnd]].data; 35 } 36 37 //delete 38 void delete(T data) { 39 if( isEmpty() ) 40 return; 41 int pos = hashFunction(data); 42 T dat = dataArr[pos].data; 43 dataArr[pos].data = null; 44 45 //to avoid moving large data block left, the data at the tail is moved to middle instead. 46 //so the pointers needs to be adjusted. 47 size--; 48 rndArr[pos] = rndArr[size]; //move pointer to middle 49 dataArr[rndArr[size]].idx = pos; // adjust the pointer in data array. 50 } 51 }when there is duplicated dataThe existence of duplicated data is further conflict with the hash table structure. To keep the up the high performance, theconflict can be resolved by a linked list (or, separate chain). But with this change, the getRandom is not random any more. Theduplicated data put extra weight on each element, so the element picked is biased. To solve this problem, each duplicatedelement has to appear in the index array. Considering the requirements, the rndAry can implement multiple link lists to store theconflict data. In that way, the data are still in an array but it has internal linked list structure to resolve the confliction.So, we can first define a new data structure: 1 class Data { ? 2 T data; 3 int prev, next; // for the linked list structure in rndArr 4 }When adding a non-existing data, new entries will be added in both dataArr and rndArr. If the data already exits in the hashtable, only put a new entry in rndArr and hook up to the existing one as a chain. When deleting a data, if the data is stillduplicated, we will remove the element from the head linked list. As we did before, the last element in rndAry should be movedto fill the gap where the data is deleted. The hash table and the rndAry should be adjusted to maintain the data integrity. If thedata being deleted is the last one in the hash table, the entry in hash table also needs to be deleted. To get a random data, wejust need to randomly pick up one element. Nothing is changed here.Unit testTo test the getRandom, we can set the random seed so the random process can be repeated. Or simply overwrite (overload)the method with a non-random version so the behavior is totally controlled.
  5. 5. Searchphone book 1. given name, find the phone number. 2. given first name, find the last name and phone number. 3. both direction 4. wild card support.submit my answer Searchcompare data structuresCompare different data structures, such as link, vector, list, queue, stack, set, and map.What are their pros and cons?submit my answer
  6. 6. Graph SearchDesign data structure to store and operate on very sparse matrix.Design data structure to store and operate on very sparse matrix, which supports following operation: 1. multiply. 2. subtract. 3. check if links exists in the matrix.origsubmit my answer Searchteams of best friendshttp://www.mitbbs.com/article_t/JobHunting/31617589.htmlsubmit my answer Searchbipartite matching problemA binary matrix is like below:A B Ca 1 0 1b 0 1 1c 1 1 1lets say person a is available for job A can you write a program to list all possible assignment combinations in a format likebelow:A B Ca b ca c bc b a( each person can only be assigned to one job)submit my answer Searchshortest path algorithmexplain shortest path algorithmsubmit my answer SearchDesign a game which transform a word to the target word. one letter is replaced at each step.Design a game: which transform a word to a target word. for example: from he ad to tail, each step, you just can replace onecharacter, and the word must be valid.oirgsubmit my answer SearchGraph traversalhttp://www.mitbbs.com/article_t/JobHunting/31650275.html
  7. 7. submit my answer Searchminimal set of words to understand half of the sentencesTheres a book and each sentence consists of several words. How to find the minimal set of words which can used by thereader to understand half of total number of the sentences. Each sentence is readable if the reader know all the words.submit my answer
  8. 8. Hash Table SearchWhat is the difference between HashTable and binary search tree?What is there time complexity of following operation? 1. insertion. 2. lookupsubmit my answer SearchHashTable knowledge How to resolve conflicts Loading factorsubmit my answer
  9. 9. Heap Searchimplement siftup (siftdown) for heaporigsubmit my answer
  10. 10. Link SearchCopy a link list with extra random pointers.There is a singly linked list with an extra pointer on each node. Those extra pointers can point to any other nodes, as shown inthe red arrows below.Duplicate this link list with O(1) space complexity.General IdeaThis question is very good for practising the deletion and insertion ofnodes in linked list.Suppose the original link is {A1, ..., A5} and the copied result is {B1,..., B5} with the same structure. 1. The first step is to insert the nodes after the original node. The {Ai, Bi} can be treated as a group and all operations can be done on those groups. 2. The next step is to mirror the extra link on Ai to Bi. 3. Finally, the merged link is split into two separate links. The newly created link list has the same structure as in the original one.The above steps can be generalizedThe idea grouping the new and old node together can be easily apply toother data structure. For example, suppose we have a binary tree withextra link on each node, and we want to duplicate the structure. 1. We can first create a new node and put it as the left child of the original node. Imagine this new node is invisible, the tree is the same as previous one. 2. Then we can mirror all links of the original tree to the new structure. 3. Finally, detach the new tree from the merged one.codeThe following code in Java is to copy a linked list with extra random link. 1 LinkNode copyLink(LinkNode link) { ? 2 if (link == null) 3 return null; 4 5 // (1) copy the link list and hook up after the original node. 6 LinkNode p = link; 7 do { 8 LinkNode p2 = new LinkNode(); 9 p2.value = new String(p.value.toLowerCase()); 10 p2.next = p.next; 11 p.next = p2; 12 p = p2.next; // NOTE: p = p.next.next; 13 } while (p != null); 14 15 // (2) copy the link list and hook up after the original node. 16 p = link; 17 do { 18 if (p.extra != null) { 19 p.next.extra = p.extra.next; 20 } 21 p = p.next.next; // NOTE: p = p.next.next; 22 } while (p != null); 23 24 // (3) split the two link lists apart. 25 p = link; 26 LinkNode link2 = p.next;
  11. 11. 26 LinkNode link2 = p.next; 27 while (p.next != null) { 28 LinkNode q = p.next; 29 p.next = q.next; 30 p = q; 31 } 32 return link2; 33 }CodeCode can be found at: http://code.google.com/p/sureinterview/source/browse/src/solution/list/CopyLinkWithExtraPointer.java SearchReverse single linked list.requires: 1. recursive method 2. iterative methodsubmit my answer Searchhow to find a circle/loop in a linked list? 1. check if a linked list has a loop. 2. if there is a loop, find the starting point of the loop.General IdeaThe "tortoise and hare" algorithm uses two pointers (tortoise and hare), which move through the link at different speeds. Thetortoise moves 1 step at a time and the hare moves 2 steps at a time. If there is a loop, the hare will meet the tortoise.To find the starting position of the loop, put the hare back to head and let it move 1 step at a time. When the hare and thetortoise meet again, the node is the starting point of the loop (A m).ProofThe proof of this method is very interesting. Denote the length of the non-loop is m, and the length of the loop part is n. Thehare and the tortoise meet at A i=A 2*i. For the tortoise, it passes i=m+a*n+c. For the hare, it passes 2*i = 2*(m+a*n+c) =m+b*n+c. c is the offset in the loop, because they are not necessarily meet at the beginning of the loop. So, m + (2a-b)*n + c= 0.After they met, the hare is set back to head and starts over again (step = 1). When the hare is moved to the head of the loop(A m), the tortoise is moved to A i+m=A m+a*n+c+m=A m+(b-a)*n=A m, which is also the head of the head of the loop. Searchfind the middle of a single linked list.find the middle of a single linked list.submit my answer
  12. 12. List SearchLongest Increasing sequence (LIS)Find a subsequence of a given sequence in which the subsequence elements are in sorted order, lowest to highest, and in whichthe subsequence is as long as possible. This subsequence is not necessarily contiguous, or unique.AlgorithmsCheck the efficient solution of longest increasing subsequence. The code can be found in algorithmist.Quick recap of the ideaThe pseudo code: 1 L = 0 ? 2 for i = 1, 2, ... n: 3 binary search for the largest positive j <= L such that X[M[j]] < X[i] (or set j = 0 if no such value exists) 4 P[i] = M[j] 5 if j == L or X[i] < X[M[j+1]]: 6 M[j+1] = i 7 L = max(L, j+1)As a quick recap of the algorithm in wiki, here is an example that explains the major steps: 1 1 3 5 7 4 6 8 <- X: the data array, M: an index array working like a stack, L: the length of M. ? 2 3 1 3 5 7 4 6 8 4 ^ processed here 5 0 1 2 3 <- M: an index array holding an increasing subsequence (replaced with smaller data). 6 - 0 1 2 <- P: the index for tracing back. Currently it is: M(L)=3 -> P(M(L))=2 -> P(P(M(L))= 1 -> P(P(P(M(L 7 8 1 3 5 7 4 6 8 9 ^ processed here 10 0 1 4 3 <- M: In M[2], 2 is replaced by 4, because X[4]=4 < X[2]=5. Note that the length of M is not change 11 - 0 1 2 1 <- P: not changed. Still is: (3) -> 2 -> 1 -> 0 12 13 14 1 3 5 7 4 6 8 15 ^ processed here 16 0 1 4 5 6 <- M: replace 3 with 5. append 6 17 - 0 1 2 1 4 5 <- P: (6) -> 5 -> 4 -> 1 -> 0 (done)Alternative solutionSort the list in O(n logn) and find the longest common subsequence in O(n2). SearchMaximum in sliding windowInput: A large integer array A[]Output: An array B[], where B[i] is the maximum value of from A[i] to A[i+w-1]General IdeaIf extra space is allowed, it should be used as a queue rather than a max heap.Check how to implement a queue with getMax operation. The sliding window is a special usage of the queue.Following is the Java implementation. 1 public Integer[] getMaxInSlideWindow(Integer[] A, Integer w) { ? 2 // invalid input 3 if (A == null || w <= 0 || A.length - w + 1 <= 0) 4 return null; 5
  13. 13. 5 6 Integer[] B = new Integer[A.length - w + 1]; 7 8 // auxiliary queue that is sorted in descending order 9 LinkedList<Integer> q = new LinkedList<Integer>(); 10 11 for (int i = 0; i < A.length; i++) { 12 // enqueue. Remove those smaller values 13 int data = A[i]; 14 while (!q.isEmpty() && q.getLast() < data) { 15 q.removeLast(); 16 } 17 q.add(data); 18 19 if (i < w - 1) { 20 continue; 21 } 22 23 // dequeue. If the current number is the maximum. Also remove it 24 // from the queue 25 Integer max = q.get(0); 26 B[i - w + 1] = max; 27 if (A[i - w + 1] == max) { 28 q.removeFirst(); 29 } 30 } 31 32 return B; 33 }CodeCode can be found at: http://code.google.com/p/sureinterview/source/browse/src/solution/search/MaximumInSlideWindow.java SearchFind the min and max in a listFind the min and max in a listFinding max needs n-1 comparison. Finding min needs additional n-2 comparison.But by splitting the number into to halves, we can save n/2 comparisons, as shown below. So the total number of comparisonis (3/2)*n - 2. 8 | 4 8 | |2 4 6 8| | | | <- save n/2 comparison.1 3 5 7 -- | | 1 5 n/2-1 | / 1 -- SearchImplement a queue with getMax operation.Implement a queue with following operations: removeFirst - remove the first element getFirst - get the value of first element addLast - append the value to the end of queue. getMax - get the maximum value of the queue.General IdeaIf extra space is available, the extra space should be used as a auxiliary queue, which is a subset of the original one and keepsorted in descending order. The head stores the current maximum value. The tail stores the last inserted element.The auxiliary queue also makes sure that each element is the largest after the previous element is popped out.Implementation 1 public void addLast(T data) { ? 2 // insert data to the data queue. 3 dataQ.add(data); 4 5 // adjust the auxiliary queue. 6 while (!auxiQ.isEmpty() && auxiQ.getLast().compareTo(data) < 0) { 7 auxiQ.removeLast();
  14. 14. 7 auxiQ.removeLast(); 8 } 9 auxiQ.add(data); //append to the end. 10 } 11 12 13 public T getMax() { 14 return auxiQ.getFirst(); 15 } 16 17 18 public T removeFirst() { 19 T data = dataQ.removeFirst(); 20 21 // adjust the auxiliary queue. Because the previous max is removed, the 22 // head (which is the current max) should be removed too. 23 if (data == auxiQ.getFirst()) { 24 auxiQ.removeFirst(); 25 } 26 return data; 27 }CodeCode can be found at: http://code.google.com/p/sureinterview/source/browse/src/solution/list/QueueWithMax.javaAlso check maximum in sliding window for its application and a related problem implement a stack with min/max operation.
  15. 15. Set SearchGiven two sets stored in single linked lists. calculate the third set = set 1 - set 2.other operations: 1. union 2. intersection.What if the set is stored in a binary search tree?submit my answer SearchHow to implement "set" data structure?origsubmit my answer
  16. 16. Stack SearchImplement an algorithm to check whether brace expressions are valid or notImplement an algorithm to check whether brace expressions are valid or not 1 boolean isGood(String s, String braces); //assume braces are valid,{}[]() ? 1. stack 2. the stack is empty after all string are read.test case: 1 ( ? 2 ) 3 () 4 ()( 5 ()) 6 )()origsubmit my answer
  17. 17. Algorithms on tree, such as traversal. SearchGiven the pre-order and in-order traversing result of a binary tree, write a function to rebuild the treeGiven the pre-order and in-order traversing result of a binary tree, write a function to rebuild the tree.submit my answer SearchHow to turn a binary search tree into a sorted array?How to turn a binary search tree into a sorted array?Node definition: 1 struct Node { ? 2 Node* left; 3 Node* right; 4 int value; 5 };submit my answer SearchTree serialization and deserializationSerialize and deserialize a tree.General ideaThe tree serialization is to save its data structure into a flat file, from which the original tree can be recovered (deserialized).There are a few ways to serialize a tree.1 Serialize the nodesA common method of serialize a tree or graph is to save the node values and their relationship. Forexample, given the tree on the right. Each node can be represented by 4 elements, (#, value, #left,#right). By listing all notes, the tree can be serialized as: 1 0, "a", 1, 2 ? 2 1, "b", 3, ^ 3 2, "c", ^, ^ 4 3, "d", ^, ^Actually, this is also the general way to serialize a graph. Following code draws this example tree inDOT language. The graph (tree) breaks down into nodes and edges, which can have differentproperties. 1 digraph{ ? 2 node [style=bold, label="N", shape=record]; 3 node0 [label="<l> | <v>A | <r>"]; 4 node1 [label="<l> | <v>B | <r>"]; 5 node2 [label="<l> | <v>C | <r>"]; 6 node3 [label="<l> | <v>D | <r>"]; 7 node0:l -> node1; 8 node0:r -> node2; 9 node1:l -> node3; 10 }During the serialization process, we need to assign each node a unique id. To efficiently look up that id, the mapping fromobject to id can be saved into a hash table. If the tree is stored in a list or array, the index of the node can be used as the idinstead. Similar hash table mapping from id to object can be used in deserialization.2 Tree traversalThe traversal result of a tree also implicitly determine its topology. For example, the pre-order traversal uniquely describe theexample tree above as.
  18. 18. 1 a b d ^ ^ ^ c ^ ^ ?The "^" is for empty node, which is necessary to recover the tree. Because a tree with n nodes has n+1 empty nodes, to savespace, multiple empty nodes can be noted as ^#. For example, the above serialized result can be revised to: 1 a b d ^3 c ^2 ?Check a slide for serializing trees.A combination of preorder and inorder traversal can also uniquely describe a tree. The example tree has preorder and inordertraversal as follows: 1 a b d c //preorder ? 2 d b a c //inorder 3 4 a (b d) [c] //preorder 5 (d b) a [c] //inorderThe first node in preorder list is the root. By searching the root in the inorder list, the traversals are partitioned into left branchand right branch. The branches can be recovered in the same way recursively. This method is not efficient in term of time andspace complexity. Saving tree size is better but is still not quite efficient.3 Newick formatNewick format is widely used in bioinformatics. It is a human readable format but needs more effort to serialize and deserialize.Following code is to deserialize the tree in format of value(<left branch>,<right branch>). The example above is serialized as0(1(2,),3). 1 private BNode makeTreeRec() throws Exception { ? 2 // 1. setup 3 BNode root = new BNode(); 4 char c = treeStr[pos]; 5 root.value = 0; 6 while (c >= 0 && c <= 9) { 7 root.value *= 10; 8 root.value += c - 0; 9 c = treeStr[++pos]; 10 } 11 12 // 2 left, root, right 13 if (c == () { 14 c = treeStr[++pos]; 15 if (c != ,) { 16 root.left = makeTreeRec(); 17 } 18 if (treeStr[pos] != ,) 19 throw new Exception(", expected at position " + pos); 20 21 c = treeStr[++pos]; // skip "," 22 if (c != )) { 23 root.right = makeTreeRec(); 24 } 25 if (treeStr[pos] != )) 26 throw new Exception(") expected at position " + pos); 27 ++pos; // --> ) 28 } 29 30 return root; 31 }CodeCode can be found at: http://code.google.com/p/sureinterview/source/browse/src/lib/tree/TreeUtil.java#172 Searchbinary tree lowest common ancestorGiven two nodes in a binary tree, find the the lowest common ancestor of the two nodes. 1. Each node has a parent node link. 2. No parent link, but the tree is binary search tree. 3. Each node also knows the level in the tree.General idea
  19. 19. 1. If the parent node link is given, we can trace each node back to the root. The problem is to check where those two linksmerge. 2. If it is a binary search tree (BST), we needs to find the node whose branch covers both nodes. Each node in BST hasa min and a max that covers some certain range.1. Given parent nodeIf the parent node link is given, the problem is to check where two links merge starting from given nodes. So, we first trace onelink back to root and put the nodes into a set. Then we trace another one back to find the first merged node, which is thelowest common ancestor.If the level of each note is given, the problem is still to find the first merged node, but the set is not necessary. 1 public BNode getLCA2(BNode root, BNode a, BNode b) { ? 2 // 1. trace one node to the root 3 Set<BNode> set = new HashSet<BNode>(); 4 BNode t = a; 5 while (t != null) { 6 set.add(t); 7 t = t.parent; 8 } 9 10 // 2. trace another node towards to root. The common ancestors are those 11 // nodes also in the set from step 1. 12 t = b; 13 while (t != null) { 14 if (set.contains(t)) 15 return t; 16 t = t.parent; 17 } 18 return null; // not found 19 }2. Binary search tree (BST)If the tree is BST without parent link, we need to start from root and check the relationship of current node and the two givennodes. If both nodes are on the left side of given node, we should move to left child. Dito for the right node.Assume the BST is defined as left < root <= right. 1 public BNode getLCA(BNode root, BNode a, BNode b) { ? 2 if (root == null || a == null || b == null) 3 return null; // input is not valid 4 5 BNode lca = null; 6 7 // let la <= lb. 8 Integer ia = (a.value < b.value ? a.value : b.value); 9 Integer ib = (a.value + b.value - ia); 10 11 BNode curNode = root; 12 while (curNode != null) { 13 /* 14 * val is the value of current node. 15 */ 16 17 // case 1. val < a <= b. Because val is on the root, the lowest 18 // common ancestor must be on the right branch. 19 if (curNode.value < ia) { 20 curNode = curNode.right; 21 continue; 22 } 23 24 // case 2. val == a <= b 25 if (curNode.value.equals(ia)) { 26 do { 27 lca = curNode; 28 if (lca == a) 29 break; 30 curNode = curNode.right; 31 if (curNode == null || !curNode.value.equals(ia)) 32 return null; // the node a does not exist. 33 } while (true); 34 35 // double check if note b is really in the tree 36 if (getInBST(lca, ib) == null) { 37 lca = null; 38 } 39 return lca; 40 } 41 42 // case 3. a < val < b 43 if (curNode.value < ib) {
  20. 20. 43 if (curNode.value < ib) { 44 lca = curNode; 45 if (getInBST(lca, ia) == null || getInBST(lca, ib) == null) { 46 lca = null; 47 } 48 return lca; 49 } 50 51 // case 4. a < val == b 52 if (curNode.value == ib) { 53 lca = curNode; 54 if (getInBST(lca, ia) == null) { 55 lca = null; 56 } 57 return lca; 58 } 59 60 // case 5. a <= b < val 61 curNode = curNode.left; 62 } 63 return null; 64 }CodeCode can be found at: solution/tree/LowestCommonAncestor.java SearchHow to detect a tree is a subtree of another tree?How to detect a tree is a subtree of another tree?submit my answer SearchFind the n-th smallest element in a binary search tree (BST). if the size of the tree is unknown. if the size of the tree is known.General IdeaTo find the n-th smallest node in a binary search tree is equivalent to finding the n-th node in a general binary tree. So we justneed to return the n-th node during the inorder traversal. If the size of each branch is known, we need to depth search for then-th node based on the size.If the size of each branch is unknownInorder transversal the tree and return the node when found. Note: 1. remember to return to upper layer when the result is found. 2. pay attention how the result is kept and returned.If the size of each branch is knownWhen the size is known, get the n-th node is like find a node in a binary search tree.CodeCode can be found at: http://code.google.com/p/sureinterview/source/browse/src/solution/tree/NthSmallestInBST.java Searchcheck a tree if it is BST.origsubmit my answer Searchre-balance BSTre-balance BSTsubmit my answer
  21. 21. SearchGiven a sorted array, build a BST and make sure the height is minimal.Given a sorted array, build a BST and make sure the height is minimal.Prove it.submit my answer Searchenumerate operator treeput operators in a list of numbers so that the result equals to a number. Give you an array of integers, ask you to writeprogram to put operators (+ - * / %) between the integers (you may put in braces wherever you want too), to have theequation equals to the result.eg: 5 * (3 + 8) % 9 = 6submit my answer Searchcheck if 2 tree nodes are related (ancestor/descendant)check if 2 tree nodes are related (i.e. ancestor-descendant) solve it in O(1) time, with O(N) space (N = # of nodes) pre-processing is allowedsubmit my answer SearchHow to turn a sorted double linked list into a binary search tree?How to turn a sorted double linked list into a binary search tree?submit my answer

×