C ++ implements a binary search tree

Source: Internet
Author: User

Implement the data structure of the Binary Search Tree and record it as follows:

# Include
 
  
Using namespace std; struct TreeNode {int val; TreeNode * left; TreeNode * right; TreeNode (int value) {val = value; left = NULL; right = NULL ;}}; class SearchTree {public: SearchTree ();~ SearchTree (); void Destory (TreeNode *); void Insertnode (int); void Preorder (TreeNode *); void Inorder (TreeNode *); void Postorder (TreeNode *); void Predisplay (); void Indisplay (); void Postdisplay (); private: TreeNode * root;}; SearchTree: SearchTree () {root = NULL;} SearchTree ::~ SearchTree () {cout <"analyze Binary Search Tree:" <
  
   
Left); Destory (node-> right); cout <
   
    
Val <"; delete node ;}} void SearchTree: Insertnode (int value) {if (root = NULL) root = new TreeNode (value ); else {TreeNode * p, * pre; pre = p = root; while (p) {if (p-> val = value) return; else if (p-> val> value) {pre = p; p = p-> left;} else {pre = p; p = p-> right ;}} p = new TreeNode (value); if (pre-> val> value) pre-> left = p; else pre-> right = p ;}} void SearchTree :: predisplay () {Preorder (root);} void SearchTree: Preorder (TreeNode * root) {if (root) {cout <
    
     
Val <"; Preorder (root-> left); Preorder (root-> right) ;}} void SearchTree: Indisplay () {Inorder (root );} void SearchTree: Inorder (TreeNode * root) {if (root) {Inorder (root-> left); cout <
     
      
Val <"; Inorder (root-> right) ;}} void SearchTree: Postdisplay () {Postorder (root) ;} void SearchTree: Postorder (TreeNode * root) {if (root) {Postorder (root-> left); Postorder (root-> right); cout <
      
        Val <"" ;}} int main () {SearchTree t; int a [] = }; int n = sizeof (a)/sizeof (a [0]); cout <"construct a binary search tree:" <
       
        

Related Article

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.