First of all, we need to mention a software called Homebrew
Homebrew is probably the best package manager on Mac. It is equivalent to Ubuntu apt and command-line app store
Homebrew
brew
Max Howell is the author of Homebrew. When he went to google for an interview, the interviewer gave a question about reversing the binary tree. However, Max Howell didn't answer it. Finally, he became a good story
Google Interviewer: when Max Howell, the star programmer, comes to our big Google, he must stay! He can't give too difficult questions or be too straightforward; so the questions should be simple and forced, and the tree structure should be more appropriate. The most common tree is the binary tree, and the most tested one is the binary search tree, so reverse the binary tree, ha ha, I'm really considerate!
Max Howell: nature makes people
class Node(object): def __init__(self, value = None): self.value = value self.left = None self.right = None class Tree(object): def __init__(self): self.root = Node() self.queue = [] pass def add(self, value): # Create a node tmp_node = Node(value) # If the root node is empty, add the root node if len(self.queue) == 0: self.root = tmp_node self.queue.append(tmp_node) # If the root node is not empty else: # Get the node whose current subtree is not full (current temporary parent node) nowRoot = self.queue[0] # If the left subtree of the temporary parent node is empty if nowRoot.left == None: nowRoot.left = tmp_node self.queue.append(tmp_node) # If the right subtree of the temporary parent node is empty else: nowRoot.right = tmp_node self.queue.append(tmp_node) # Clear parent from queue (this parent is now full) self.queue.pop(0) # Sequential traversal def recursion_lvr(self, root): # If the node is empty, return if not root: return self.recursion_lvr(root.left) print(root.value) self.recursion_lvr(root.right) # Invert binary tree def reverse_tree(self, root): if not root: return # Get the root node of the current left and right subtrees tmp_left_node = root.left tmp_right_node = root.right # Reverse left and right subtrees of binary trees root.left = tmp_right_node root.right = tmp_left_node # Add left and right subtrees to the new sequence self.reverse_tree(root.left) self.reverse_tree(root.right) def main(): tree = Tree() for i in range(1,8): tree.add(i) tree.recursion_lvr(tree.root); tree.reverse_tree(tree.root) print("Results after reversal:") tree.recursion_lvr(tree.root); if __name__ == '__main__': main()
This story tells us that algorithm is very important, but not too serious