Tree and Graph

Source: Internet
Author: User

Tree charts and graphs are one of the most common questions during the interview.

Key points:

1. Tree, binary tree, binary search tree, binary seach tree, defined.

2. binary tree traversal: Preorder, inorder, and postorder. Layered traversal is very important, and many companies like to take the test. In fact, it is the breadth of the graph that gives priority to breath first search.

3. Representation of the graph: base table and base matrix.

4. graph traversal: depth-first DFS and breadth-first BFs. the time complexity of these two Traversal Algorithms is O (| v | + | E |), and V is the number of nodes, E is the number of edges, but the two traversal methods have different application scenarios. This is based on the question.

A binary search tree described by Java: it includes new, inserted nodes, search nodes, middle-order traversal, pre-order traversal, and post-order traversal.

Note that the average query time complexity of the Binary Search Tree is O (logn), which is the same as that of the binary search.

public class BinarySearchTree {private TreeNode root;private class TreeNode {int data;TreeNode leftChild;TreeNode rightChild;TreeNode(int v) {data = v;leftChild = null;rightChild = null;}}/** * create an empty binary tree */public BinarySearchTree() {root = null;}/** * search for a node with given data will use a helper function: TreeNode * lookup(TreeNode node, int data). */public TreeNode lookup(int data) {return lookup(root, data);}private TreeNode lookup(TreeNode node, int data) {if (node == null) {return null;} else {if (data == node.data) {return node;} else if (data < node.data) {return lookup(node.leftChild, data);} else {return lookup(node.rightChild, data);}}}/** * insert a new node to the this binary tree with the help of another * function: TreeNode insert(TreeNode node, int data) */public void insert(int data) {root = insert(root, data);}/** * recursively insert a new node */private TreeNode insert(TreeNode node, int v) {if (node == null) {return new TreeNode(v);} else {if (v <= node.data) {node.leftChild = insert(node.leftChild, v);} else {node.rightChild = insert(node.rightChild, v);}return node;}}/** * inOrder traverse */public void printInOrder(TreeNode node) {if (node.leftChild != null) {printInOrder(node.leftChild);}System.out.print(node.data + " ");if (node.rightChild != null) {printInOrder(node.rightChild);}}/** * preOrder traverse */public void printPreOrder(TreeNode node) {System.out.print(node.data + " ");if (node.leftChild != null) {printPreOrder(node.leftChild);}if (node.rightChild != null) {printPreOrder(node.rightChild);}}/** * postOrder traverse */public void printPostOrder(TreeNode node) {if (node.leftChild != null) {printPostOrder(node.leftChild);}if (node.rightChild != null) {printPostOrder(node.rightChild);}System.out.print(node.data + " ");}}

Okay. Let's get started.

1. implement a function to check if a binary tree is balanced. for the purpose of this question, a balanced tree is defined to be a tree such that the heights of the two Subtrees of any node never differ by more than one. check whether a binary tree is balanced. Here, the balanced binary tree indicates that the height difference between left and right Subtrees of any node cannot exceed 1.

Source: cracking the coding interview 5th edition, charpter4, question1.

Analysis:First, how to obtain the height of a binary tree? Using Recursion, most algorithms of Binary Trees use recursion algorithms. The height of a binary tree: that is, the height of the left and right subtree of the root node plus 1. The time complexity of this algorithm is O (n) because it accesses each node once.

public int getHeight(TreeNode node){if(node == null){return 0;}int leftHeight = getHeight(node.leftChild);int rightHeight = getHeight(node.rightChild);return Math.max(leftHeight, rightHeight)+1;}

Method 1: Top and bottom, check the height difference between left and right subtree of the root node, check the height difference between left subtree and right subtree... Until all nodes are checked.

Pseudocode:

boolean isBalanced(root){leftHeight = getHeight(root.leftChild);rightHeight = getHeight(root,rightChild);if(abs(leftHeight-rightHeight) > 1){return false;}else{return isBalanced(root.leftChild)&&(root.rightChild);}}

Here, getheight is repeatedly called on each node, so the time complexity is O (n ^ 2). During the interview, if you make an O (N ^ 2) you have to think about it. There may be better algorithms. Especially the tree. If each node can solve the problem only once, it can achieve O (n ).

Method 2: Bottom-up: Check whether the Left and Right Subtrees are balanced. If the imbalance ends, check the height difference between the left and right Subtrees. In this way, each node is only accessed once, so the time complexity is O (n ). That is, the balance check is completed every time the height of the left and right subtree is calculated. If the balance is set, the height of the subtree is returned. Otherwise, a flag, such as-1, is returned.

Java code: http://pastebin.com/VNn7D85q here the checkheight function completes the above functionality.

Finally, we have to insert a statement about how to delete a binary tree. Generally, deleting multiple nodes may lead to unbalanced binary trees. The balance here does not mean that the height of all left and right Subtrees is the same, but the difference is within a certain range, for example, the difference value specified by this question is 1. Sometimes the marked as deleted method is used to delete objects. In fact, there is no real deletion. If you delete elements and keep a tree in balance at all times, you need to rotate the nodes to reconstruct a tree. There are many rotating operations, including left-hand and right-hand operations. It is complicated, so it will not appear in the interview questions in general. For more information, see
Data Structures and algorithm analysis in C 2nd edition of Mark Allen Weiss. In this section, the AVL Tree and the red/black tree have detailed rotation operations and implementations.

2. given a sorted (increasing order) array, write an algorithm to create a binary search tree with minimal height. A binary search tree with the minimum height is generated based on a given sort (ascending) array.

Source: cracking the coding interview 5th edition, charpter4, question3.

Analysis:If you traverse the BST binary sorting tree (hereinafter referred to as BST) in the middle order, the result is an array in ascending order. This property is very important and can be used to detect whether a binary tree is BST.In this case, the minimum height is required, that is, the balance as much as possible. Obviously, arrays are constantly separated from the center to form left and right Subtrees.

Java code: http://pastebin.com/4BxK03hS here uses a helper function. The time complexity of this solution is O (n), because each element of the array is only accessed once.


3. Implement a function to check if a tree is a binary search tree. check whether a binary tree is a binary sorting tree.

Source: cracking the coding interview 5th edition, charpter4, question5.

Analysis Solution: method 1Here, we can directly use the nature of the previous question, that is, if a binary tree is BST, its central order traversal is an incremental array. Therefore, You Can slightly modify the central traversal algorithm. Each traversal records the previous element and compares it with the element value of the current node.

static int lastVisit = Integer.MIN_VALUE;public static boolean isBST(TreeNode n){if(n == null){return true;}if(!isBST(n.leftChild)){return false;}if(n.data < lastVisit){return false;}lastVisit = n.data;if(!isBST(n.rightChild)){return false;}return true;}

Method 2:Take advantage of the Nature of BST:That is, the value of the left child of any node, which is smaller than the value of the node and smaller than the value of the right child of the node,Note thatArbitraryNode. And the left subtree'sAllThe node value is smaller than the value of its parent node.AllThe value of the right subtree.

Example: 10

4 12

2 11

This is not a BST, because the node 11 location is wrong, it should be on the right of 10, the left of 11.

The top-down method is used here: the value range of each layer node is obtained. If it is not in this range, it is not BST. For example, for a BST, the value range of Layer 10 is [min, Max], the value range of Layer 2 left subtree is [min, 10], and the value of right subtree is [10, max], to the third layer, the range of the Left subtree of 4 is [min, 4], and the range of the right subtree is [4, 10.

Java code: http://pastebin.com/9XEDhF2D the algorithm's time complexity is O (n), because each node is accessed once.

4. mirror a tree. mirror a tree.

Analysis:If you have understood the above questions, the problem will be very simple and you will use the most intuitive recursive algorithm. There is no difficulty in this question. Companies with better points may ask this question as soon as they come up.

The image of a tree is symmetric, that is, the left and right subtree of all nodes are paired.

For example, 10 images are 10 images.

4 12 12 4

2 11 2 11

The result of the Middle-order traversal will become an array in descending order,

Remember, recursive algorithms must not forget the base case. Generally, when the input is null, there are some special values.

Java code:

public void mirror(TreeNode n){if(n == null){return;}mirror(n.leftChild);mirror(n.rightChild);TreeNode temp = n.leftChild;n.leftChild = n .rightChild;n.rightChild = temp;}

5. given a binary tree and a number, check if there exists a path from root to leaf, that the total sum of every node's value is equal to the number. given a binary tree and a number, determine whether there is such a path from the root node to the leaf node. The sum of values of each node in the path is equal to the input integer.

Analysis:A simple question, if you are familiar with recursion. Code: the base case here indicates that the input root is null, and the input number is determined to be 0.

public boolean hasPathSum(TreeNode n, int sum){if(n == null){return (sum == 0);}int sum_left = sum - n.data;return hasPathSum(n.leftChild,sum_left)||hasPathSum(n.rightChild, sum_left);}

6. Print all paths from root to every leaf node. Print all paths from the root node to the leaf node.

Analysis:In fact, it is a tree DFS, and DFS is implemented recursively. Specifically, you can access the root node first, then the left subtree, and then the right subtree. Each time you access the deepest leaf node, this path is printed, therefore, a variable is required for recursive calls to save all nodes in the path accessed so far.

Java code: the time complexity of the http://pastebin.com/zgXAxuBa algorithm is O (logn), because a total of nodes on the logn layer.

7. given a binary tree in which each node contains a value. design an algorithm to print all paths which sum to a given value. note that a path can start or end anywhere in the tree. A binary tree is provided. Each node of the tree contains a value, a value is provided, and all paths are printed so that the sum of the values of all nodes in the path is equal to the value. This path can start or end with any node in the tree.

Source: cracking the coding interview 5th edition. Chapter 4, Q 9.

Analysis:It looks like the above two questions: Sum, print the path, but here there is a condition that this path can start and end from any node.

It is easy to think of the brute force solution. DFS traverses each node. Each time a node is accessed, the DFS traverses the sum from the node to the next. If the sum is equal to the given value, the path is output; if the value is less than, the system continues to go down. If the value is greater than, the system returns.

Java: http://pastebin.com/F7WVeSW6

But wait !!! The node value may be negative! If there is a path {2, 5, 6-2,-4}, and {2, 5}, the same path is 7 !!

In fact, you only need to slightly modify the code. In the Helper function, remove the two conditions except the same.

So what is the time complexity of this algorithm? O (nlogn), because n nodes are iterated, and each node to be iterated accumulates a total of n logn layers.


8. given two binary trees: T1 which has millions of nodes, and T2 which has hundreds of nodes. design an algorithm to decide if T2 is a subtree of T1. Two Binary Trees, T1 and T2, T1 with millions of nodes and T2 with hundreds of nodes, determine whether T2 is a child tree of T1.

Source: cracking the coding interview 5th edition. Chapter 4, Q 8.

Analysis:The simplest way to determine how a tree is equal to another tree/subtree is to retrieve the traversal string by using both the central order and one of the first and second order traversal, then, determine whether the two strings are equal or not. Note that it is necessary to traverse in order, and then select one in the first and later order to uniquely identify a tree. You can read this article as to why and how to get the third result from two traversal methods. Http://www.cnblogs.com/zhangchaoyang/articles/2008434.html

Suffix tree can be used to determine how a string is a substring of another string. I will add this in the following article. I remember that Amazon died in this issue... I didn't know what trie was at that time. Now I am very fond of asking questions during interviews!

However, I have already mentioned that T1 is very big and big. Although you can use the above method, it is definitely not what the interviewer wants to see, you need to propose the above solution. It's one thing. I don't think it's another thing. Because T1 is very large, you need a lot of memory to store the values of all nodes. Of course, you can justify not saying that the data structure is too big to have that T1 value... Okay, you can't.

How can this problem be solved?

Traverse each node of T1. When a node is encountered, its value is the same as the value of the root node of T2, and the Child tree of T1 and t2. To determine whether it is the same subtree, we use recursive methods to determine whether it is the same subtree. Therefore, we need two functions: one issubtree (T1, T2) and the other issametree (T1, T2 ).

JAVA Implementation: http://pastebin.com/MF1rFPEF



Refer:

[1]. http://cslibrary.stanford.edu/110/BinaryTrees.html

[2 ].
Cracking the coding interview 5th edition.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.