Common Binary Tree Problems and Solutions

Source: Internet
Author: User

The common problems of Binary Trees are as follows. If they are solved, they are as easy as linked lists: the only difference is that Binary Trees are non-linear structures. Common problems are as follows:

Binary Tree Problems
1. Three travel methods of Binary Trees:

Binary Tree problem 1. three methods of traveling with binary trees: 2. how to print Binary Tree node data layer by layer from the top 3. how to determine whether a binary tree is a balanced binary tree 4. design an algorithm to find the nearest common parent node of any two nodes on the binary tree. If the complexity is O (n2), no score is obtained. 5. How can we achieve forward/backward/Central traversal of Binary trees without recursion? 6. Finding all paths for a specific value in a binary tree 7. How to write a program and put an ordered integer array in a binary tree? 8. judge whether the integer sequence is the result of the sequential traversal of the Binary Search Tree 9. search for binary tree images 10. A binary sorting tree (that is, the binary search tree BST), so that f = (maximum value + minimum value)/2, design an algorithm to find the node closest to the F value and greater than the F value. If the complexity is O (n2), no score is obtained. 11. Convert the binary search tree into a sorted two-way linked list 12. Print all the paths in the binary tree (similar to question 5)

3. How to determine whether a binary tree is a balanced binary tree
4. design an algorithm to find the nearest common parent node of any two nodes on the binary tree. If the complexity is O (n2), no score is obtained.
5. How can we achieve forward/backward/Central traversal of Binary trees without recursion?
6. Find all paths for a specific value in the binary tree (note that the path is to the leaf node)
7. How to write a program and put an ordered integer array into a binary tree?
8. Determine whether the integer sequence is a result of post-order traversal of the Binary Search Tree.
9. Search for Binary Tree Images
10. A binary sorting tree (that is, the binary search tree BST), so that f = (maximum value + minimum value)/2, design an algorithm to find the node closest to the F value and greater than the F value. If the complexity is O (n2), no score is obtained.
11. Convert the binary search tree into a sorted two-way linked list
12. Print all the paths in the binary tree (similar to question 6)

Solution:

1. Three Methods of traveling in a binary tree: Any book with a data structure is described and skipped;

2. How to print Binary Tree node data layer by layer from the top?

Set a queue. If the queue is not empty, add the left and right children of the first element to the queue (if the left and right children are not empty), and right the first element of the queue, as shown in:

Shows the binary tree:

The entire process is as follows:

Naturally, a, B, c, d, e, f are output.

3. How can I determine whether a binary tree is balanced?

It's too easy to use recursion: Determine whether the depth difference between left and right subtree of the root node is less than or equal to 1 (here we need to use the depth method). If yes, the root node is balanced. Then, you can determine whether the left and right children of the root node are balanced. Continue until the leaf node is met. If not, false is returned immediately;

Calculate an algorithm to find the nearest common parent node of any two nodes on the binary tree. If the complexity is O (n2), no score is obtained.

First, find the two vertices key1 and key2, and record the paths path1 and path2 of these two vertices. Then, find that the first vertex K meets the requirements, and set key1 to <k <key2.

Suppose key1 = 5, key2 = 7. Obviously, path1 {8, 6}, path2 {8, 6, 7 }. The k that satisfies the first key1 <k <key2 is 6. Therefore, K = 6.

For details about how to find path1 and path2, refer to question 12.

5. How can we achieve forward/backward/Central traversal of Binary trees without recursion? (Netease asked during the interview. It was a tragedy and suddenly got stuck)

Reading books, basically any data structure book, mainly using stacks.

6. Find all the paths for a specific value in the binary tree?

Solve 12 questions first and access any path from the binary tree to the leaf node. After this problem is solved, we can naturally sum up to see if conditions are met.

7. How to write a program and put an ordered integer array into a binary tree?

Recursion or recursion:

With int array [begin, end], first add array [(begin + end)/2] to the binary tree, and then recursively create array [begin, (begin + end) /2-1] and array [(begin + end)/2 + 1, end]. Pay attention to writing the function form. Everything is natural.

8. Determine whether the integer sequence is the result of post-order traversal of the Binary Search Tree?

Let's take a look at the next traversal: The left and right root, so the most accessed node is actually the root node root of the entire Binary Tree: Then, find the first Root Node B that is greater than the value of the node. B is the leftmost node of the right subtree of the root node (greater than the smallest node of the root node ). In this case, the left subtree of root is located in front of B. Since it is the result of the binary search tree traversal, The traversal results between B and root should be greater than B. Take this as the condition for judgment.

9. How can I find a binary tree image?

Or use recursion: as long as the node is not empty, switch the pointer of the left and right subtree, find the image of the Left subtree separately, and then find the image of the right subtree until the node is null.

10. A binary sorting tree (that is, the binary search tree BST), so that f = (maximum value + minimum value)/2, design an algorithm to find the node closest to the F value and greater than the F value. If the complexity is O (n2), no score is obtained.

First, in BST, the minimum value is the leftmost node, and the maximum value is the rightmost node.
After finding min and Max respectively, find F. Then, use the search function to find a node greater than F.
The complexity is logn.

11. Convert the binary search tree into a sorted two-way linked list

12. Print all paths in the binary tree

The path is a set of vertices from the root node to the leaf node.

Or recursion: Use a list to save the nodes that pass through. If it is already a leaf node, print all the contents of the list. If not, add the nodes to the list, the function is then recursively called, except that the entry parameter is changed to the left and right subtree of the node.

The procedure is as follows:

Answer 1: I have read a book. Answer 2: // Question 2: how to print Binary Tree node data from the top layer void printatlevel (bitnode * root) {vector <bitnode *> vector; vector. push_back (Root); While (! Vector. Empty () {bitnode * TMP = vector. Front (); If (TMP-> lchild! = NULL) vector. push_back (TMP-> lchild); If (TMP-> rchild! = NULL) vector. push_back (TMP-> rchild); cout <TMP-> data <Endl; vector. pop_back () ;}}// Question 3: how to determine whether a binary tree is a balanced binary tree int isbalencedtree (treenode * root) {If (root = NULL) return 0; int depth1 = getdepth (root-> lchild); int depth1 = getdepth (root-> rchild ); if (depth1 = depth1 | depth1 = depth1 + 1 | depth1 = depth1-1) return 1; elsereturn 0; int flag1 = isbalencedtree (root-> lchild ); int flag2 = isbalencedtree (roo T-> rchild); If (flag1 & flag2) return 1; elsereturn 0 ;}// Question 4: design an algorithm, find the nearest common parent node of any two nodes on the binary tree. If the complexity is O (n2), no score is obtained. Int getpublicancestors (treenode * root, int key1, int key2) {treenode * PTR = root; int path1 [1000]; int pathlen1 = 0; while (PTR! = NULL) {If (key1 = PTR-> data) {path1 [pathlen1] = PTR-> data; pathlen1 ++; printarray (path1, pathlen1); break ;} elseif (PTR-> DATA> key1) {path1 [pathlen1] = PTR-> data; pathlen1 ++; PTR = PTR-> lchild ;} elseif (PTR-> data <key1) {path1 [pathlen1] = PTR-> data; pathlen1 ++; PTR = PTR-> rchild;} PTR = root; int path2 [1000]; int pathlen2 = 0; while (PTR! = NULL) {If (key2 = PTR-> data) {path2 [pathlen2] = PTR-> data; pathlen2 ++; printarray (path2, pathlen2); break ;} elseif (PTR-> DATA> key2) {path2 [pathlen2] = PTR-> data; pathlen2 ++; PTR = PTR-> lchild ;} elseif (PTR-> data <key2) {path2 [pathlen2] = PTR-> data; pathlen2 ++; PTR = PTR-> rchild;} int I = pathlen1-1; // key1 and key2 are ordered. If (key2 <key1) {key2 = key2 ^ key1; key1 = key2 ^ key1; key2 = key2 ^ key1 ;}for (; I> 0; I --){ If (key1 <path1 [I] & path1 [I] <key2) {int result = path1 [I]; return result ;}}// Question 6: find out the void findpath (treenode * root, int path [], int pathlen, int expectedsum, int currentsum) {If (root = NULL) for all paths for a value in the binary tree) return; currentsum + = root-> data; path [pathlen] = root-> data; pathlen ++; if (currentsum = expectedsum & root-> lchild = NULL & root-> rchild = NULL) {printarray (path, pathlen );} if (root-> lchild! = NULL) {findpath (root-> lchild, path, pathlen, expectedsum, currentsum);} If (root-> rchild! = NULL) {findpath (root-> rchild, path, pathlen, expectedsum, currentsum) ;}currentsum-= root-> data ;}// Question 7: how to write a program, put an ordered integer array in a binary tree? Void createtreefromarray (int A [], int begin, int end, treenode ** root) {If (begin> end) return; else {* root = (treenode *) malloc (sizeof (treenode); int mid = (begin + end)/2; (* root)-> DATA = A [Mid]; (* root) -> rchild = NULL; (* root)-> lchild = NULL; createtreefromarray (A, begin, mid-1, & (* root)-> lchild); createtreefromarray (, mid + 1, end, & (* root)-> rchild) ;}// Question 8: judge whether the integer sequence is post-Binary Search Tree // The result of sequential traversal int isposttravers E (int A [], int begin, int end) {If (begin> = END) return 1; else {int root = A [end]; int lroot; int I; int location = begin; for (I = begin; I <end; I ++) {if (a [I]> root) {location = I; lroot = A [I]; break ;}}for (I = location + 1; I <end; I ++) {if (a [I] <lroot) {return 0 ;}} int flag1 = isposttraverse (A, begin, location-1); int flag2 = isposttraverse (A, location, end-1 ); if (flag1 & flag2) return 1; elsereturn 0;} // Question 9: Obtain the binary tree image void changemirror (treenode ** root) {If (* root = NULL) return; else {treenode * temp = (* root) -> lchild; (* root)-> lchild = (* root)-> rchild; (* root)-> rchild = temp; changemirror (& (* root) -> lchild); changemirror (& (* root)-> rchild) ;}/// question 10: 10. A binary sorting tree (that is, the binary search tree BST), so that f = (maximum value + minimum value)/2, design a calculation // method to find the node closest to the F value and greater than the F value. If the complexity is O (n2), no score is obtained. Int findnearmid (treenode ** root) {treenode * PTR = * root; int min, Max; while (PTR! = NULL) {min = PTR-> data; PTR = PTR-> lchild;} printf ("the Min is % d \ n", min); PTR = * root; while (PTR! = NULL) {max = PTR-> data; PTR = PTR-> rchild;} printf ("the max is % d \ n", max ); int half = (min + max)> 1; printf ("half is % d \ n", half); PTR = * root; while (1) {If (PTR-> data 


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.