Binary Tree Insertion

Source: Internet
Author: User
/* Function: Insert a node into the subnode of the node in the binary tree. Input: P, C, rl P: the node will be inserted into the subnode of the node pointed to by P. C: pointing to the node to be inserted rl: 0 indicates that the node is inserted to the left subtree. 1 indicates that the node is inserted to the right subtree. Output: bool */template <typename T> bool binarytree <t> :: insertchild (btnode <t> * P, btnode <t> * C, int RL) {If (p) {If (RL = 0) // Insert the left node to P {C-> rchild = p-> lchild; // The original left subtree of the p node becomes the right subtree of C p-> lchild = C; // C becomes the left subtree of p} else {C-> rchild = p-> rchild; P-> rchild = C;} return true;} else return false ;}

There is a binary tree and a node as follows. P points to node 2 and C points to node 6. Now we need to insert C into the left subtree of P.

RL is 0, and the right sub-node pointer of C (originally pointing to null) points to the left sub-node of P (4)

Point the pointer to the left subnode of P to the node pointed to by C (6)

Child node inserted

 

Another implementation form:

Template <typename T> bool binarytree <t>: insertchild (t e, t c, int RL) {btnode <t> * PE, * PC; pe = searchnode (E); If (PE) {Pc = new btnode <t>; PC-> DATA = C; PC-> lchild = NULL; PC-> rchild = NULL; If (RL = 0) {PC-> rchild = pe-> lchild; pe-> lchild = pc ;} else {PC-> rchild = pe-> rchild; pe-> rchild = pc;} return true ;} cout <"Node" <e <"does not exist" <Endl; return false ;}

 

 

 

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.