Basic Topic learning of binary tree (EPI)

Source: Internet
Author: User

1. Determine whether a binary tree is a balanced binary tree.

Binary Trees are defined using recursive methods. Therefore, binary trees have natural recursive attributes. Therefore, the recursive solution is simple in solving Binary Tree problems. A balanced binary tree is defined as a balance binary tree between the left and right Subtrees. The height difference between the left and right Subtrees cannot exceed 1. All three conditions are indispensable.

According to the definition of recursion, the height of the sub-tree must be returned and the balance attribute of the sub-tree must be returned. Therefore, the recursive algorithm for determining the balance binary tree needs to pass two parameters, therefore, the recursive function prototype is defined as int balancedtree (treenode * root, bool & isbalanced). The returned height is returned. The reference parameter is also used as the return value to indicate whether the subtree is balanced, this is easier to implement. (The recursion of many algorithms in a binary tree requires this method to return multiple variables. You can practice it. Two impressive similarities:. the maximum path in a binary tree (the path is defined from any node to any other node), B. for more questions about the common ancestor, see ).

One way to broaden the horizon: One way to reduce the space complexity step by step is to use first-order traversal, and then use a global variable to record the maximum depth of the stack in real time. In the third volume of computer programming art, page 460 of sorting and searching proves that the height of the Balance Tree of N nodes does not exceed HN = 1.20.5lg (n/2 + 3)-0.3277. If the stack height exceeds this height during traversal, the tree is unbalanced.

2. First, set a concept. If the absolute value of the difference between the number of nodes in the left subtree and the number of nodes in the right subtree is not greater than K, the node is not k-balanced.

Question: Given a binary tree, find a node in the binary tree that is not k-balanced, and its successor nodes are K-balanced nodes.

Recursive search: you can set a global node variable, which is initialized to null. After finding a node in recursion, the variable is assigned to the global node. If the global variable is not null in recursive functions, the variable is directly returned. The Return Value of the recursive function is the number of nodes in the current tree. Number of nodes in the current tree = number of left subtree nodes + number of right subtree nodes + 1. the recursive end condition is that the node is not null, and the number of returned nodes is 0. The unique value assigned to the global node variable is the first time when the absolute value of the difference between the left and right subtree exceeds K. At this time, it is returned along the recursive path.

3. Determine whether a binary tree is an image.

The leetcode contains the original question, which is easy to use. It also uses recursive judgment, but the initial condition is left subtree node and right subtree node. Recursive Function isequalric (treenode * left, treenode * Right). First, the root node must be equal, and then the recursive isequalric (left-> right, right-> let) must be satisfied) <G id = "1"> image tree </G>. Recursive code is concise.

4. Implement a binary tree locking mechanism. The condition is that if a node's successor node or ancestor node is locked, the node cannot be locked. Implement islock (), lock (), and unlock () operations. The time complexity is limited to O (1), O (h), O (h ), h indicates the height of the tree. Assume that the binary tree has a pointer to the parent node.

Each node adds a flag to implement the islock () Operation of O (1.

In addition, the flag operation of the node is maintained during lock () and unlock () maintenance. When locking and unlocking, you need to consider the ancestor and the child. The ancestor can traverse and obtain the state within the time complexity of O (h. If the child node is considered one by one, it may need O (n. Therefore, you cannot traverse them one by one,

You can save a variable in the node to check whether the child node is locked. When the variable is locked, the flag is set one by one when the ancestor is traced back up.

Therefore, when unlocking, you need to release the lock icon of the child in the parent node and change whether the lock icon is locked.

5. Given a binary tree representation with a parent node pointer, use the extra space of O (1) to traverse the binary tree. The structure of the tree cannot be modified.

The Morris method can achieve binary tree traversal with the spatial complexity of O (1), but the tree structure needs to be changed temporarily during the traversal process. Therefore, this traversal algorithm is NOT thread-safe.

The topic has a parent node pointer, so Stack tracing is not required. The parent node pointer can be used for backtracking, so the time complexity of O (1) can be reached.

The algorithm template sets the current node pointer cur and the previous node pointer pre Based on the subsequent traversal implemented by the stack. Then we will discuss it in three situations,

Pre = NULL | pre-> left = cur | pre-> right = cur, which belongs to the traversal down condition, continue to traverse down, temporarily use the next pointer to point to the next node

Cur-> left = pre, which is a situation where the left subtree and the traversal up are just traversed.

Cur-> right = pre, which belongs to the situation where the right subtree and the traversal up are just traversed.

6. Obtain the Simple Method for traversing the k-th node in the binary tree in sequence, and calculate the output of the k-th node. the time complexity is O (n ). If each node in a given binary tree contains the number and number of all its subtree nodes, how can we optimize the algorithm for finding the K node. The time complexity can be optimized to O (h), and H is the height of the tree.

In fact, it is easy to get the idea of the question, and you can quickly scale down the problem. View the number of left subtree of the current node,

If the number of left subtree of the current node is K, we can see that the current node is the desired node. If the number of nodes in the left subtree is greater than or equal to K, you can narrow down the problem to find the K node in the left subtree.

If the number of left subtree of the current node is less than the K-1, we can see that the K node in the right subtree, find the K-(number of left subtree + 1) in the right subtree.

7. Restore a binary tree by traversing in the central or backward or first order.

The question in leetcode has a simple idea. You can determine the root node in the descending or descending order, split the middle order traversal based on the root node, and call the left and right subtree recursively.

In addition, the binary tree cannot be restored in the first and last orders. Therefore, this problem is generally caused by matching another traversal order in the middle order.

Expansion problem: Constructing the max tree based on a given array A: the max tree defines that the root node is the maximum value in the array A. Assuming that the coordinates of the maximum value are m, the left subtree is composed of a [0: s-1] and the right subtree is composed of a [M + 1, N]. Recursive construction of the Left subtree and the right subtree is based on the maximum value. Design an efficient method for constructing the max tree.

A more intuitive method can be used to find the maximum value each time. In this way, the time complexity of each search for the maximum value is O (n), so the total time complexity is O (n ^ 2 ). If you want to optimize it, you must consider optimizing it from the perspective of obtaining the maximum value. You can save the maximum values from left to right and from right to left. Or pre-processing can be completed by using monotonous Queues with Stack functions.

8. If a first-order traversal result containing null nodes is given, can O (n) restore a binary tree? What about backward and middle order?

Here, we can use the stack to push the two nodes from the stack and the current node into the stack. Finally, it is a complete binary tree.

The traversal in the middle order cannot be unique to restore the binary tree. Because all tree traversal results have the same sequence.

Think about a sequence traversal binary tree that contains null values (which is also very simple ).

9. Connect all subnodes of a binary tree to a linked list.

Recursion, and then determine whether the child node is connected if the child node is connected. Save a global header node variable.

10. Design a method for outputting a binary tree peripheral node. Peripheral node explanation: sequence a, B, d, g, J, K, L, M, N, I, F, C to be output

The previous question has completed the linked list of leaf nodes, and output is not difficult. Therefore, the difficulty of this question is to output the left periphery and the right periphery.

I first thought about whether to use Morris to traverse the output peripheral nodes. Later I drew an incomplete binary tree and found it quite complicated.

The answer is very concise. The peripheral node on the left is characterized by the peripheral node of the current node, the left node of the node is the peripheral node, if the left node is empty, the right sub-node of the node is the peripheral node.

The peripheral node on the right is characterized by the peripheral node of the current node, the right node of the node is the peripheral node, and if the right node is empty, the left child node of the node is the peripheral node.

Note: The output sequence of the left and right peripheral nodes is different. On the right side, you can refer to the output list in reverse order to implement recursion quite concisely.

11. Find the first common group method for the two nodes in the binary tree.

The idea is similar to the idea of the first question: recursion, but two parameters need to be passed (or the recent common ancestor uses global variables)

A. If both nodes are in the left subtree, recursive left subtree to find the nearest common ancestor.

B. If the two nodes are in the left and right subtree, the current node returns.

C. If the current node is one of the nodes, the current node is returned.

(This algorithm has never been coding. You need to practice it as a basic operation)

12. If a binary tree contains a parent pointer, can the method of finding the closest common ancestor of two nodes in the binary tree be optimized?

With the parent pointer, you can find the first cross node from the given two nodes at the same time, so the problem is converted to two single-chain tables to find the first cross node.

A. the scan method is three times. First, the length of the two linked lists is counted from the current node to the end node, and then the distance between the two linked lists is counted, then the two pointers move at the same time. The first convergence is the recent common ancestor.

B. If the above method is used, the time complexity is the depth of the deepest node. Because the length needs to be measured. Then, I further asked this question to further optimize the time complexity.

At that time, there was indeed no way to further optimize the time complexity, and the idea was blocked. I did not expect the space to change the time. The question does not require space complexity, so I should consider sacrificing space.

The policy is to use the hash table to traverse two nodes each time and add them to the hash table. At the same time, if the traversal node already exists in the hash table, it indicates that the node is the first to join. (Space for Time)

13. Given a string s and a series of string set D, find the shortest string prefix in S, satisfying that the prefix is not the prefix of any string in the d set.

You can use the trie tree to obtain the shortest public prefix. (For strings, the efficiency of the trie tree is higher than that of the hash tree. The failure of the FB interview means that you are not the first to think about this concept and are not proficient in it)

The trie tree letter indicates that in the edge extension, the node generally stores true or false to indicate whether the word has arrived, or the vector <string> container to indicate all words that can be reached by the path, determine the trie tree structure based on the question.

(Exercise required)

Basic Topic learning of binary tree (EPI)

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.