Binary search tree and balanced binary tree

Source: Internet
Author: User

Binary search Tree

Binary search Tree properties: For each node in the tree x, all key values in its left subtree are less than the keyword value of x, and all the key values in its right subtree are greater than the keyword value of x.

The average depth of the binary lookup tree is O (logn), and the following is a look at its related operation functions.

Delete a binary tree (recursive form):

void Makeempty (TreeNode *root) {if (root = NULL) return; Makeempty (Root->left); Makeempty (Root->right) free (root);}

Find a node in the binary lookup tree:

treenode* Find (TreeNode *root, int x) {if (root = NULL) return null;if (Root->val > x) return Find (Root->left, x); El Se if (root->val < x) return Find (Root->right, x); Elsereturn root;}

Find the maximum value in the binary lookup tree:

Recursive version treenode* Findmax (TreeNode *root) {if (root = null) return null;if (root->right = null) return root-> Rightelsereturn Findmax (root->right);} Iteration version treenode* Findmax (TreeNode *root) {if (root = null) return Null;while (root->right! = null) {root = Root->right ;} Retur root;}

  Before writing the algorithm, it is really important to write the test case first, because the boundary value of the test case is the exit of the recursive function.

Binary search Tree insert operation:

The insertion of a binary lookup tree is simple because the first node to be established must be the root, and then the insertion of each node must be somewhere in the leaf node.

treenode* Insert (TreeNode *root, int x) {if (root = NULL) {root = (treenode*) malloc (sizeof (TreeNode)); root->val = x; Root->left = Null;root->right = NULL;} Else{if (Root->val > x) root->left = insert (Root->left, x), else if (Root->val < x) Root->right = insert (Root->right, x);} return root;}

  

  

Two fork find tree and balanced binary 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.