Topic: Input Two binary trees A and B, to determine whether the tree B is a substructure
BOOL Ischildtree (node * father, node * son)
{
if (father = = null && son = null) return
true;
if (father = = null && son!= null) return
false;
if (Father!= null && son = null) return
true;
If the current node is the same, determine if the left and right subtree is a substructure if
(father->data = = Son->data)
{return
ischildtree (Father->left, son- >left) && Ischildtree (Father->right, son->right);
}
Determines whether the son subtree is a Zuozi of the child structure
if (Ischildtree (Father->left, son)) return
true;
Determine if the son subtree is a substructure of the right subtree
if (Ischildtree (Father->right, son)) return
true;
return false;
}
Topic: Search for recent public ancestor LCA (Lowest Common Ancestor)
Node* Getlca (node* root, node* x, node* y)
{
if (root = null) return null;
if (x = = Root | | | y = = root) return
root;
node* pleft = Getlca (Root->left, x, y);
node* pright = Getlca (root->right, x, y);
if (Pleft = NULL) return
pright;
else if (pright = NULL) return
pleft;
else return root;
}
We get the path of root node x and the path to node y respectively, because this path starts with the node, and the lowest common parent node is the last common node in the path, that is, LCA.
Get root node Phead to Pnode path bool Getnodepath (node* phead, node* pnode, std::list<node*>& path) {if (Phead = = Pnode
) return true;
Path.push_back (Phead);
BOOL found = false;
if (phead->left!= NULL) found = Getnodepath (Phead->left, Pnode, Path);
if (!found && phead->right) found = Getnodepath (phead->right, Pnode, Path);
if (!found) Path.pop_back ();
return found; ///From two lists path1 and path2 to get the last common node treenode* lastcommonnode (const std::list<treenode*>& path1, const std::
list<treenode*>& path2) {std::list<treenode*>::const_iterator Iterator1 = Path1.begin ();
Std::list<treenode*>::const_iterator Iterator2 = Path2.begin ();
treenode* pLast = NULL;
while (Iterator1!= path1.end () && Iterator2!= path2.end ()) {if (*iterator1 = = *iterator2)
PLast = *iterator1;
iterator1++;
iterator2++;
return pLast; }
Topic: Finding the lowest common ancestor (LCA) of a binary search tree (BST)
Using the nature of BST: Search from the root node, when the first encounter with the value of the current node is between two of the given node value, the current node is the LCA to be found.
node* Findlca (node* root,int x, int y)
{
Node * t = root;
while (1)
{
if (T->data > x && t->data > y)
t = t->left;
else if (T->data < x && t->data < y)
t = t->right;
else return t;
}
}
Topic: Looking for the K element in the sequence traversal sequences of BST
void Findk (node* p, int& k)
{
if (!p | | | k < 0) return;
Findk (P->left, k);
--K;
if (k = = 0)
{
print p->data;
return;
}
Findk (P->right, k);
}
Question: Find the distance between the two nodes farthest apart in the binary tree
To find the farthest distance of two nodes, the actual is to find the diameter of the binary tree. This problem can be converted to "the maximum of the left and right subtree height of each node of the binary tree".
int Treeheight (node* root, int& max_distance)
{
if (root = NULL)
{
max_distance = 0;
return 0;
}
int left_height,right_height;
if (root->left)
left_height = Treeheight (root->left,max_distance) +1;
else
left_height = 0;
if (root->right)
right_height = Treeheight (root->right,max_distance) +1;
else
right_height = 0;
int distance = left_height + right_height;
if (Max_distance < distance) max_distance = distance;
Return (Left_height > Right_height left_height:right_height);
int Treediameter (node* root)
{
int max_distance = 0;
if (root) treeheight (root, max_distance);
return max_distance;
}
Title: Find the maximum distance of the nodes in the binary tree: If we look at the two-fork tree as a graph, the lines between the parent-child nodes are considered bidirectional, and the number of edges between the two nodes is defined as "distance". (This problem is to find the distance between the two nodes farthest from the binary tree, the code is from "beauty of Programming")
Node definition typedef struct NODE {node * left;
Node * RIGHT;
int maxleft;
int maxright;
Char Chvalue;
}node,*pnode;
Maximum distance int maxlen = 0;
Find the maximum distance of a node in a binary tree void Findmaxlength (node* root) {if (root = NULL) return;
If the Zoozi tree is empty, the maximum distance to the left of the node is 0 if (root->left = = NULL) root->maxleft = 0;
If the right subtree is empty, the maximum distance to the right of the node is 0 if (root->right = = NULL) root->maxright = 0;
If the Zoozi tree is not empty, recursively looks for the longest distance to the left if (root->left!= NULL) findmaxlength (root->left);
If the right subtree is not empty, recursively looks for the longest distance to the right (root->right!= NULL) findmaxlength (root->right);
Computes the Zuozi longest node distance if (Root->left!= NULL) {int tempmax = 0;
if (Root->left->maxleft > Root->left->maxright) Tempmax = root->left->maxleft;
else Tempmax = root->left->maxright;
Root->maxleft = tempmax+1;
}//Compute the longest node distance of the right subtree if (root->right!= NULL) {int tempmax = 0; if (root->right->Maxleft > Root->right->maxright) Tempmax = root->right->maxleft;
else Tempmax = root->right->maxright;
Root->maxright = tempmax+1; }//Update maximum distance if (Root->maxleft+root->maxright > MaxLen) maxlen = Root->maxleft+root->maxrigh
T }
Topic: Reconstruction of binary trees, through the first sequence traversal and the sequence traversal of the series can only determine a binary tree (through the sequence of sequential and sequential traversal can also uniquely determine a binary tree, but not through the first sequence and sequential traversal sequence to uniquely determine the two-fork tree)
The binary tree void ReBuild (char* ppreorder,char* pinorder,int ntreelen,node** proot) {//Check boundary condition if (ppreor) is reconstructed by first order traversal and sequence traversal sequences Der = = NULL | |
Pinorder = = NULL) return;
Gets the first node of the sequence traversal node* temp = new node;
Temp->data = *ppreorder;
Temp->left = NULL;
Temp->right = NULL;
If the node is empty, copy the current node to the root node if (*proot = NULL) *proot = temp;
If the current tree length is 1, it is already the last node if (Ntreelen = 1) return;
Looking for subtree length char* porginorder = Pinorder;
char* pleftend = Pinorder;
int ntemplen = 0;
Find the end of Zuozi while (*ppreorder!= *pleftend) {if (Ppreorder = null | | pleftend = NULL) return;
Record the temporary length to avoid overflow ntemplen++;
if (Ntemplen > Ntreelen) break;
pleftend++;
//Find left subtree length int nleftlen = (int) (pleftend-porginorder);
Find the right subtree length int nrightlen = ntreelen-nleftlen-1; Reconstructs the left subtree if (Nleftlen > 0) ReBuild (ppreorder+1,pinorder,nleftlen,& (*proot)->left));
Rebuilds the right subtree if (Nrightlen > 0) ReBuild (ppreorder+nleftlen+1,pinorder+nleftlen+1,nrightlen,& (*proot)-
>right)); }
Title: Enter an integer and a tree of two yuan. A path is formed from the root node of the tree and down to all nodes that have passed through the leaf node. Prints all paths that are equal to the input integer.
For example, enter the integer 22 and the following two-dollar Tree
10
/ \
5 12
/ \
4 7
Then print out two paths: 10, 12 and 10, 5, 7.
Analysis: This is a test of Baidu, the basic data structure of the tree and the understanding of recursive functions. When accessing a node, add the node to the path and accumulate the value of the current node. If the current node is a leaf node and the current path is exactly equal to the input integer, the current path conforms to the requirement and prints it out. If the current node is not a leaf node, it continues to access its child nodes. After the current node access is complete, the recursive function will automatically return to the parent node. So we're going to delete the current node on the path and subtract the value of the current node before the function exits, to make sure that the path is exactly the path from the root node to the parent node when the parent node is returned. It's not hard to see that the data structure of the saved path is actually a stack structure, because the path is consistent with the recursive call state, and the recursive call is essentially a process of stack and stack.
#include <iostream> #include <vector> using namespace std;
struct Node {int value;
Node* left;
node* right;
Node () {left = null; right = NULL;}
Node (int v) {value = v; left = null; right = NULL;}};
void Findpath (node* root,vector<int>& nodes,int sum) {if (root = NULL) return;
Nodes.push_back (Root->value);
if (Root->left = = NULL && Root->right = null) {if (Root->value = sum) {
for (int i=0; i<nodes.size (); i++) cout<<nodes[i]<< "";
cout<<endl; } else {if (root->left!= NULL) {Findpath (root->left,nodes,sum-root->v
Alue);
} if (Root->right!= NULL) {Findpath (root->right,nodes,sum-root->value);
} nodes.pop_back ();
int main () {Node *tmp;
node* root = new Node (10);
TMP = new Node (5); Root-> left = tmp;
TMP = new Node (12);
Root->right = tmp;
TMP = new Node (4);
Root->left->left = tmp;
TMP = new Node (7);
Root->left->right = tmp;
Vector<int> v;
Findpath (root,v,22);
return 0; }
Title: Enter an array of integers to determine if the array is the result of the subsequent traversal of a two-dollar lookup tree. Returns False if it returns true.
For example, enter 5, 7, 6, 9, 11, 10, 8, because this sequence of integers is a sequential traversal of the following tree:
8
/ \
6 10
/ \ / \
5 7 9 11
So returns True. If you enter 7, 4, 6, 5, no tree's subsequent traversal of the result is this sequence, so return false.
Analysis: In subsequent traversal of the resulting sequence, the last element is the root node of the tree. Scan this sequence from the beginning, elements that are smaller than the root node should be in the left half of the sequence, and all elements should be larger than the root nodes, since the first element that is larger than the root to the front of the root is the same as the tree's right subtree. According to this division, the sequence is divided into the left and right parts, we recursively confirm that the two parts of the sequence is not a two-yuan lookup tree.
BOOL Verifysquenceofbst (int squence[], int length)
{
if (squence = NULL | | | length <= 0) return
false;
Root of a BST is at the "end of" post order traversal squence
int root = squence[length-1];
The nodes in left sub-tree are less than the root
int i = 0;
for (; i < length-1; + + i)
{
if (Squence[i] > root) break
;
The nodes in the right sub-tree are greater than the root
int j = i;
for (; J < Length-1; + + j)
{
if (Squence[j] < root) return
false
;
Verify whether the left sub-tree is a BST
bool-left = true;
if (i > 0) Left
= Verifysquenceofbst (squence, i);
Verify whether the right sub-tree are a BST
bool right = true;
if (I < length-1) Right
= Verifysquenceofbst (squence + i, length-i-1);
Return (left && right);
Topic: How to write a program that puts an ordered array of integers into a two-fork search tree.
Analysis: This article examines the two-fork search tree's contribution method. The algorithm design of the tree must associate with recursion, because the tree itself is the definition of recursion.
node* array_to_tree (int array[], int start, int end)
{
if (Start > End) return NULL;
int m = start + (End-start)/2;
node* root = new Node (array[m]);
Root->left = Array_to_tree (array, start, m-1);
Root->right = Array_to_tree (array, m+1, end);
return root;
}
node* array2tree (int array[], int n)
{return
array_to_tree (array,0,n-1);
}
Title: Enter a two-yuan lookup tree to convert the two-yuan lookup tree into a sorted two-way list. The request cannot create any new nodes, only the pointer is adjusted. Like two dollars to find a tree
10
/ \
6 14
/ \ / \
4 8 12 16
Converted into two-way linked list 4=6=8=10=12=14=16.
Analysis: This is Microsoft's face test. A lot of tree-related topics are used to solve the idea of recursion, the subject is no exception. Here we use two different recursive ideas to analyze.
Thinking one: When we arrive at a certain node to adjust the subtree with the node as the root node, the left subtree is first adjusted, the left subtree is transformed into a sorted left sub list, and the right subtree is transformed to the right sub list. The last link is the leftmost node of the Zoozi list (the maximum node of the left subtree), the leftmost node of the current node and the right sub-list (the smallest node of the right subtree). Recursively adjusts all nodes from the root node of the tree.
Idea two: We can traverse the whole tree in sequence. The tree is traversed in this way, and is accessed first by smaller nodes. If we each visit a node, assuming that the previously visited node has been adjusted to a sorted two-way list, we then link the current node to the end of the list. Once all the nodes have been accessed, the entire tree is converted into a sorted two-way list.
The data structure that defines the two-dollar lookup tree node is as follows:
struct Bstreenode//A node in the binary search trees
{
int m_nvalue;//value of node
Bstreenode *m_pleft//left child of node
Bstreenode *m_pright; Right child of Node
};
Train of thought a corresponding code:
Covert a sub binary-search-tree into a sorted double-linked list//Input:pnode-the head of the Sub tree//A Sright-whether Pnode is the right child of it parent//Output:if Asright is true, return the least node in the SUB-TR
EE//Else return to the greatest node in the sub-tree bstreenode* convertnode (bstreenode* pnode, bool asright) {
if (!pnode) return NULL;
Bstreenode *pleft = NULL;
Bstreenode *pright = NULL;
Convert the left sub-tree if (pnode->m_pleft) Pleft = Convertnode (Pnode->m_pleft, false); Connect the greatest node in the "left Sub-Tree" to "current node if (pleft) {pleft->m_pright = PNo De M_pright Pointer works as the "next" pointer pnode->m_pleft = Pleft;
M_pleft Pointer works as the "previous" pointer}//Convert to right sub-tree if (pnode->m_pright)
Pright = Convertnode (Pnode->m_pright, true); Connect The least node in the rightSub-Tree to the current node if (pright) {pnode->m_pright = Pright;
Pright->m_pleft = Pnode;
} bstreenode *ptemp = Pnode; If The current node was the right child of it parent,//return the least node in the tree whose root is the Curre
NT node if (asright) {while (ptemp->m_pleft) ptemp = ptemp->m_pleft; }//If The current node is the "left" child of it Parent,//return the greatest node in the ' tree whose ' root is t
He current node else {while (ptemp->m_pright) ptemp = ptemp->m_pright;
return ptemp; //Covert A binary search tree into a sorted double-linked list//input:the head of the tree//output:the head of Sorte D double-linked List bstreenode* Convert (bstreenode* pheadoftree) {//As we want to return the head of the sorted dou
ble-linked list,//We set the second parameter to is true return Convertnode (Pheadoftree, true); }
Idea two corresponds to the code:
Covert a sub binary-search-tree into a sorted double-linked list//Input:pnode-the head of the Sub tree//p
Lastnodeinlist-the Tail of the double-linked list void Convertnode (bstreenode* pnode, bstreenode*& plastnodeinlist)
{if (Pnode = NULL) return;
Bstreenode *pcurrent = Pnode; Convert the left sub-tree if (pcurrent->m_pleft!= NULL) convertnode (Pcurrent->m_pleft, Plastnodeinli
ST);
Put the "current" node into the double-linked list pcurrent->m_pleft = plastnodeinlist;
if (plastnodeinlist!= NULL) plastnodeinlist->m_pright = pcurrent;
Plastnodeinlist = pcurrent; Convert the right sub-tree if (pcurrent->m_pright!= NULL) convertnode (Pcurrent->m_pright, Plastnodei
Nlist); }//Covert a binary search tree into a sorted double-linked list//input:pheadoftree-the head of the tree//output:the Head of sorted double-linked list bstreenode* Convert (bstreenode* pheadoftrEE) {Bstreenode *plastnodeinlist = NULL;
Convertnode (Pheadoftree, plastnodeinlist);
Get the ' head of the ' double-linked list//M_pleft pointer works as the ' previous ' pointer in the double-linked list
Bstreenode *pheadoflist = plastnodeinlist;
while (pheadoflist && pheadoflist->m_pleft) pheadoflist = pheadoflist->m_pleft;
return pheadoflist; }