Two-fork Tree

Source: Internet
Author: User

A binary tree is a tree structure with a maximum of two subtrees per node. The subtree is often referred to as the left subtree and the right subtree (subtree). Binary trees are often used to implement a two-fork search tree and a two-fork heap.

Traversal order

traversal is one of the most basic operations of the tree, so-called traversal of the binary tree, that is, according to a certain rules and order all the nodes of the binary tree, so that each node is visited once, and only be visited once. Since the binary tree is a nonlinear structure,the traversal of a treein essence, each node of a two-fork tree is converted into a linear sequence to represent it. set L, D, R to Traverse Zuozi, access the root node and traverse right subtree, there are three cases of traversal of a binary tree: The DLR (called the root sequence traversal), LDR (known as the root sequence traversal), LRD (called the post-root sequence traversal). First Order Traversalfirst, the root is accessed, and then the left (right) subtree is traversed, and then the right (left) subtree is iterated through the first sequence. Middle Sequence Traversalfirst, the middle sequence traverses the left (right) subtree, then accesses the root, and the final middle sequence traverses the right (left) sub-tree. Post-post traversalThe first step is to traverse the left (right) sub-tree, then go through the right (left) subtree and finally access the root. The Two fork tree node is defined as follows:
struct Binarytreenode
{
int m_nvalue;
binarytreenode* M_pleft;
binarytreenode* M_pright;
};

List of topics:

1. Finding the number of nodes in a binary tree
2. Find the depth of the binary tree
3. Pre-sequence traversal, middle sequence traversal, post-order traversal
4. Layered traversal of the binary tree (level from top to bottom, left to right)
5. Turn the two-fork lookup tree into an ordered doubly linked list
6. Find the number of nodes in the K-tier of the binary tree
7. Finding the number of leaf nodes in a binary tree
8. Determine if two binary trees are of the same structure
9. Determine if the binary tree is not a balanced two-pronged tree
10. Find the image of the binary tree
11. Finding the lowest common ancestor node of two nodes in a binary tree
12. Finding the maximum distance of a node in a binary tree
13. Rebuilding the binary tree from the sequence traversal sequence and the middle sequence traversal sequences
14. Judging the binary tree is not a complete binary tree

Detailed Answer:

1. Finding the number of nodes in a binary tree
Recursive solution:
(1) If the binary tree is empty, the number of nodes is 0
(2) If the binary tree is not empty, the number of binary tree nodes = The number of left subtree nodes + the number of right child tree nodes + 1
The reference code is as follows:

<strong>int getnodenum (Binarytreenode * proot) {    if (proot==null)  //Recursive exit--end recursion           return 0;return Getnodenum (Proot->m_pleft) + getnodenum (proot->m_pright) + 1; }</strong>

2. Find the depth of the binary tree

Recursive solution:
(1) If the binary tree is empty, the binary tree has a depth of 0
(2) If the binary tree is not empty, the depth of the binary tree = max (left subtree depth, right subtree depth) + 1
The reference code is as follows:

<strong>class test{int getdepth (Binarytreenode * proot) {if (Proot = NULL)//Recursive exit return 0;int depthleft = getdepth (P Root->m_pleft)///Zuozi depth int depthright = getdepth (proot->m_pright);//depth of right subtree//two fork tree depth, whichever is greater. +1 is the root node return depthleft > Depthright? (Depthleft + 1): (Depthright + 1); }};</strong>

3. Pre-sequence traversal, middle sequence traversal, post-order traversal
Recursive recursion method for pre-sequence traversal:
(1) If the binary tree is empty, empty operation
(2) If the binary tree is not empty, the root node is accessed, the pre-sequence traverses the left subtree, and the pre-sequence traverses the right sub-tree
The reference code is as follows:

void Preordertraverse (Binarytreenode * proot) {if (Proot = = NULL) return;<span style= "color: #ff6666;" >visit (Proot); </span>//Access root node Preordertraverse (proot->m_pleft); The anterior sequence traverses the left subtree Preordertraverse (proot->m_pright); Pre-order traversal right subtree}

Recursive method of Middle sequence traversal
(1) If the binary tree is empty, empty operation.
(2) If the binary tree is not empty, the middle sequence traverses the left subtree, accesses the root node, and the middle sequence traverses the right sub-tree
The reference code is as follows:

<strong>void inordertraverse (Binarytreenode * proot) {if (Proot = = NULL) return;inordertraverse (pRoot->m_ Pleft); The middle sequence traverses the left subtree <span style= "color: #ff6666;" >visit (Proot); </span>//Access root node Inordertraverse (proot->m_pright); Middle sequence traverse right subtree}</strong>

Recursive recursion method for post-sequential traversal
(1) If the binary tree is empty, empty operation
(2) If the binary tree is not empty, the post-order traversal of the left sub-tree, the order to traverse the right subtree, access to the root node
The reference code is as follows:

<strong>void postordertraverse (Binarytreenode * proot) {if (Proot = = NULL) return; Postordertraverse (Proot->m_pleft); Post-sequential traversal left subtree postordertraverse (proot->m_pright); Post-step traversal right subtree <span style= "color: #ff6666;" >visit (Proot);</span>//Access root node}</strong>

4. Layered traversal of the binary tree (level from top to bottom, left to right)

Equivalent to breadth-first search, using queue implementation. The queue is initialized, and the root node is pressed into the queue. When the queue is not empty, do the following: Popup a node, access, if the left child node or right child node is not empty, press it into the queue.

<p> void Leveltraverse (Binarytreenode * proot) {if (proot==null) return;  Queue<binarytreenode *>q;  Q.push (Proot);   while (!q.empty ()) {Binarytreenode *pnode =q.front ();//Front q.pop ();          Visit (Pnode);//Access Node </p><p> if (pnode->m_pleft! = NULL) Q.push (pnode->m_pleft);    if (pnode->m_pright! = NULL) Q.push (pnode->m_pright); } return; }</p>

5. Turn the two-fork lookup tree into an ordered doubly linked list

Requires that new nodes cannot be created, only pointers are adjusted.
Recursive solution:
(1) If the binary tree lookup tree is empty, no conversion is required, the first node corresponding to the doubly linked list is null, and the last node is null
(2) If the binary lookup tree is not empty:

If the left dial hand tree is empty, the first node corresponding to the two-way ordered list is the root node, and no other action is required on the left;
If the left dial hand tree is not empty and the left subtree is converted, the first node of the binary lookup tree corresponding to the two-way ordered list is the first node of the two-way ordered linked list after the Zuozi transformation, and the last node of the two-way ordered linked list after the root node and the left subtree is connected;
If the right subtree is empty, the last node corresponding to the two-way ordered list is the root node, and no other action is required on the right;
If the right subtree is not empty, the last node corresponding to the two-way ordered linked list is the last node of the two-way ordered linked list after the right subtree is converted, and the first node of the two-way ordered linked list that is transformed by the root node and the right subtree is connected.

The reference code is as follows:

/****************************************************************************** parameter: pRoot: Two fork Find tree root node pointer pfirstnode: The first node pointer of the two-way ordered linked list Plastnode: The last node pointer of a two-way ordered list after conversion ***************************************************************** /void Convert (Binarytreenode * proot, Binarytreenode * & Pfirstnode, Binarytreenode * & Plastnode) {Binarytreenode *pfirstleft, *plastleft, * pfirstright, *plastright;if (proot = = null) {Pfirstnode = null; Plastnode = Null;return;} if (Proot->m_pleft = = null) {//If the left dial hand tree is empty, the first node corresponding to the two-way ordered list is the root node Pfirstnode = proot;} Else{convert (Proot->m_pleft, Pfirstleft, plastleft);//Two forks the first node of the lookup tree corresponding to the two-way ordered list is the first node of the two-way ordered list after the Zuozi transformation Pfirstnode = pfirstleft;//the last node of the two-way ordered list after the root node and the left subtree is converted Proot->m_pleft = Plastleft;plastleft->m_pright = Proot;} if (proot->m_pright = = NULL) {//corresponds to the last node of the bidirectional ordered list is the root node Plastnode = proot;} Else{convert (Proot->m_pright, Pfirstright, plastright);//The last node corresponding to the two-way ordered list is the last node of the two-way ordered list after right subtree conversion plastnode = plastright;//The first node of the two-way ordered linked list after the root node and right subtree are connected ProOt->m_pright = Pfirstright;pfirstright->m_pleft = Proot;} return;}

6. Find the number of nodes in the K-tier of the binary tree
Recursive solution:
(1) If the binary tree is empty or k<1 returns 0
(2) If the binary tree is not empty and k==1, return 1
(3) If the binary tree is not empty and k>1, the number of nodes in the record k-1 layer and the number of nodes in the right subtree k-1 layer are returned.
The reference code is as follows:

int Getnodenumkthlevel (Binarytreenode * proot, int k)  {if (proot==null| | K<1) return 0;if (k==1) return 1;int numleft=getnodenumkthlevel (proot->m_pleft,k-1);//The number of k-1 layer nodes in the right subtree int numright =getnodenumkthlevel (proot->m_pright,k-1);//Record K-1 layer node number return numleft+numright;}

7. Finding the number of leaf nodes in a binary tree

Recursive solution:
(1) If the binary tree is empty, return 0
(2) If the binary tree is not empty and the left and right sub-tree is empty, return 1
(3) If the binary tree is not empty, and the left and right subtrees are not empty at the same time, return the number of leaves in the left subtree plus the number of leaf nodes in the subtree.
The reference code is as follows:

int Getleafnodenum (Binarytreenode * proot) {if (proot = = null) return 0;if (Proot->m_pleft = = null && proot->m _pright = = NULL) return 1;int numleft = Getleafnodenum (proot->m_pleft); Record number of leaf nodes int numright = Getleafnodenum (proot->m_pright); The number of leaf nodes in the right subtree return (Numleft + numright);}

8. Determine if two binary trees are of the same structure

Data content is not considered. The same structure means that the corresponding Zuozi and corresponding right sub-tree are all structurally identical.
Recursive solution:
(1) If two binary trees are empty, return to True
(2) If two binary trees are empty and the other one is not empty, return false
(3) If two binary trees are not empty, if the corresponding Saozi right subtree are isomorphic back to true, the other return false
The reference code is as follows

BOOL STRUCTURECMP (Binarytreenode * pRoot1, Binarytreenode * pRoot2)  {if (proot1==null&&proot2==null) Return True;if (proot1==null| | Proot2==null)//There is an empty, one is not empty, return false return false; BOOL Resultleft = structurecmp (Proot1->m_pleft, proot2->m_pleft); Compare corresponding left dial hand tree    bool Resultright = structurecmp (Proot1->m_pright, proot2->m_pright);//Compare Right subtree   return ( Resultleft && resultright);  }

9. Determine if the binary tree is not a balanced two-pronged tree

Recursive solution:
(1) If the binary tree is empty, return true
(2) If the binary tree is not empty, if Saozi right subtree are AVL tree and Saozi right subtree height difference is not greater than 1, return true, other return False
Reference code:

BOOL Isavl (Binarytreenode * proot, int & height) {if (proot = = null)//empty tree, return true {height = 0;return true;} int Heightleft;bool resultleft = Isavl (Proot->m_pleft, heightleft); int Heightright;bool resultright = IsAVL (pRoot- >m_pright, Heightright); if (resultleft && resultright && abs (heightleft-heightright) <= 1)//Saozi The right subtree is AVL, and the height difference is not greater than 1, which returns true {height = max (heightleft, heightright) + 1;return true;} Else{height = Max (Heightleft, heightright) + 1;return false;}}


10. Find the image of the binary tree

Recursive solution:
(1) If the binary tree is empty, return null
(2) If the binary tree is not empty, seek the mirror of Saozi right subtree, then swap Saozi right sub-tree
The reference code is as follows:

Binarytreenode * MIRROR (Binarytreenode * proot) {if (proot = = null)//return Nullreturn NULL; Binarytreenode * Pleft = Mirror (proot->m_pleft); Left subtree Image binarytreenode * pright = Mirror (proot->m_pright); Find right subtree mirror        //swap Saozi right subtree Proot->m_pleft = Pright;proot->m_pright = Pleft;return proot;}

11. Finding the lowest common ancestor node of two nodes in a binary tree
Recursive solution:
(1) If two nodes are in the Saozi right subtree of the root node, the root node is returned
(2) If all two nodes are in the left subtree, the left subtree is processed recursively, and if two nodes are in the right subtree, the right subtree is recursively processed.
The reference code is as follows:


BOOL FindNode (Binarytreenode * proot, Binarytreenode * pnode) {if (Proot = null | | pnode = NULL) return false;if (proot = = P Node) return True;bool found = FindNode (Proot->m_pleft, Pnode); if (!found) found = FindNode (Proot->m_pright, Pnode) ; return found;} Binarytreenode * Getlastcommonparent (Binarytreenode * proot,                                      binarytreenode * pNode1,                                      Binarytreenode * pNode2) {if (FindNode (Proot->m_pleft, pNode1)) {if (FindNode (Proot->m_pright, PNode2)) return Proot;elsereturn Getlastcommonparent (Proot->m_pleft, PNode1, PNode2);} Else{if (FindNode (Proot->m_pleft, PNode2)) return Proot;elsereturn getlastcommonparent (Proot->m_pright, PNode1 , PNode2);}}

Recursive method is very inefficient, there are a lot of repeated traversal, the following look at the non-recursive solution.
Non-recursive solution:
The path from the root node to the two nodes is then compared to the node of the corresponding path, and the last identical node is their lowest common ancestor node in the binary tree.
The reference code is as follows:

BOOL Getnodepath (Binarytreenode * proot, Binarytreenode * pnode, List<binarytreenode *> & Path) {if (Proot = = Pnode) {path.push_back (proot); return true;} if (Proot = = NULL) return false;path.push_back (proot); bool found = False;found = Getnodepath (Proot->m_pleft, Pnode, Path), if (!found) found = Getnodepath (proot->m_pright, Pnode, Path), if (!found) Path.pop_back (); return found;} Binarytreenode * Getlastcommonparent (Binarytreenode * proot, Binarytreenode * pNode1, Binarytreenode * pNode2) {if (PRoot = = NULL | | PNode1 = = NULL | | PNode2 = = NULL) return null;list<binarytreenode*> path1;bool bResult1 = Getnodepath (Proot, PNode1, path1);list< binarytreenode*> Path2;bool bResult2 = Getnodepath (Proot, PNode2, path2); if (!bresult1 | |!bresult2) return NULL; Binarytreenode * PLast = null;list<binarytreenode*>::const_iterator Iter1 = Path1.begin ();list< Binarytreenode*>::const_iterator iter2 = Path2.begin (); while (Iter1! = Path1.end () && iter2! = path2. End ()) {if (*iter1 = = *iter2) PLast = *iter1;elsebreak;iter1++;iter2++;} return pLast;}


On the basis of the above algorithm, the distance between any two nodes in the binary tree can be obtained by a slight change.
12. Finding the maximum distance of a node in a binary tree
That is, the distance between the two nodes farthest apart in the binary tree.
Recursive solution:
(1) If the binary tree is empty, return 0, and record the depth of the Saozi right subtree, all 0
(2) If the binary tree is not empty, the maximum distance is either the maximum distance from the left subtree, or the maximum distance from the right subtree, or the maximum distance from the left subtree node to the root node and the maximum distance from the right subtree node to the root node, while recording the maximum distance from the Saozi node to the root node in the right child tree.

The reference code is as follows:

int getmaxdistance (Binarytreenode * proot, int & maxleft, int & maxright) {//Maxleft, the node in the left subtree farthest from the root node//maxright , the node in the right subtree is farthest away from the root node if (proot = = NULL) {maxleft = 0;maxright = 0;return 0;} int Maxll, MAXLR, MAXRL, Maxrr;int maxdistleft, maxdistright;if (proot->m_pleft! = NULL) {maxdistleft = GetMaxDistance ( Proot->m_pleft, MAXLL, MAXLR); maxleft = max (MAXLL, MAXLR) + 1;} Else{maxdistleft = 0;maxleft = 0;} if (proot->m_pright! = NULL) {maxdistright = Getmaxdistance (Proot->m_pright, MAXRL, MAXRR); maxright = max (MaxRL, MAXRR) + 1;} Else{maxdistright = 0;maxright = 0;} Return Max (Max (Maxdistleft, maxdistright), maxleft+maxright);}

13. Rebuilding the binary tree from the sequence traversal sequence and the middle sequence traversal sequences

In a binary tree sequence, the first element is always the value of the root node of the tree. In the middle sequence traversal sequence, the value of the Zuozi node is located to the left of the value of the root node, and the value bit of the node of the right subtree
To the right of the root node's value.
Recursive solution:
(1) returns null if the pre-order traversal is empty or the middle sequence traversal is empty or the number of nodes is less than or equal to 0.
(2) Create the root node. The first data of the pre-sequence traversal is the data of the root node, and the position of the root node is found in the middle sequence traversal, and the pre-order and the Saozi of the right subtree are respectively learned.
Sequence, rebuilding left and right subtrees.

Binarytreenode * Rebuildbinarytree (int* ppreorder, int* pinorder, int nodenum) {if (Ppreorder = null | | pinorder = NULL | | Nodenum <= 0) return NULL; Binarytreenode * Proot = new binarytreenode;//The first data of a pre-sequence traversal is the root node data Proot->m_nvalue = ppreorder[0];p root->m_pleft =  Null;proot->m_pright = null;//Find the position of the root node in the middle sequence traversal, in the middle sequence traversal, the root node to the left of the left dial hand tree, the right is a subtree int rootpositioninorder = -1;for (int i = 0; i < Nodenum; i++) if (pinorder[i] = = proot->m_nvalue) {rootpositioninorder = I;break;} if (Rootpositioninorder = =-1) {throw std::exception ("Invalid input."); Rebuild left subtree int nodenumleft = rootpositioninorder;int * Ppreorderleft = ppreorder + 1;int * pinorderleft = pinorder;proot-> M_pleft = Rebuildbinarytree (Ppreorderleft, Pinorderleft, nodenumleft);//Rebuilding Right sub-tree int nodenumright = nodenum-nodenumleft-1 ; int * Ppreorderright = ppreorder + 1 + nodenumleft;int * pinorderright = pinorder + nodenumleft + 1;proot->m_pright = Rebuildbinarytree (Ppreorderright, Pinorderright, nodenumright); return proot;}

Similarly, there is a middle sequence traversal sequence and a post-order traversal sequence, a similar method can reconstruct the binary tree, but the pre-sequence traversal sequence and sequential traversal sequence of different recovery of a binary tree, proved slightly.
14. Determine if the binary tree is not a complete binary tree
If the depth of the two fork tree is H, except for the H layer , the nodes of the other layers (1~h-1) reach the maximum number, and all nodes in the H layer are continuously concentrated on the leftmost side, which is the complete
Two fork tree. The
has the following algorithm to traverse the binary tree hierarchically (top to bottom, left to right), and when the left subtree of a node is empty, the right subtree of the node must be empty, and the left
right subtree of the node that is traversed must be empty, otherwise it is not a complete binary tree.

BOOL Iscompletebinarytree (Binarytreenode * proot) {if (Proot = = NULL) return False;queue<binarytreenode *> Q;q.push (proot); bool Musthavenochild = False;bool result = True;while (!q.empty ()) {Binarytreenode * Pnode = Q.front (); Q.pop (); if ( Musthavenochild)//A node with a vacant tree has appeared, which must be a leaf node (left and right subtree empty) {if (Pnode->m_pleft! = NULL | | Pnode->m_pright! = NULL) { result = False;break;}} Else{if (Pnode->m_pleft! = NULL && pnode->m_pright! = null) {Q.push (pnode->m_pleft); Q.push (pnode-> M_pright);} else if (pnode->m_pleft! = null && Pnode->m_pright = = null) {Musthavenochild = True;q.push (pnode->m_ Pleft);} else if (Pnode->m_pleft = = NULL && pnode->m_pright! = null) {result = False;break;} Else{musthavenochild = True;}}} return result;}



Two-fork Tree

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.