insert node in binary search tree

Binary Sort Tree, also known as Binary Search Tree, also known as Binary Search Tree.

definition:

A binary sorted tree is either an empty tree or a binary tree with the following properties:
(1) If the left subtree is not empty, the value of all nodes on the left subtree is less than or equal to the value of its root node;
(2) If the right subtree is not empty, the value of all nodes on the right subtree is greater than or equal to the value of its root node;
(3) The left and right subtrees are also binary sorting trees;
 
as the picture shows:
 
1 <? php
 2  // binary search tree 
3  include "show.php"; // implemented a print method 
4  
5  class tree{
 6      public  $value ;
 7      public  $left = null ;
 8      public  $right = null ;
 9      
10      public  function __construct( $value )
 11      {
 12          $this ->value = $value ;
 13      }
 14  }
15  
16  /* *
 17  * $header tree root node
 18   */ 
19  function add(& $header )
 20  {
 21      $nodes = [2, 1, 4, 3, 6 ];
 22      foreach ( $nodes  as  $v )
 23      {
 24          insert_node( $header , $v );
 25      }
 26  }
 27  
28  // Binary search tree insert node (non-recursive), the inserted nodes are all leaf nodes 
29  function insert_node(& $header ,$node )
 30  {
 31      // handle the case of only one node 
32      if ( $header == null )
 33      {
 34          $header = new tree( $node );
 35          return ;
 36      }
 37      
38      // handle multiple nodes case 
39      $p = $header ;
 40      $pre = $header ;
 41      while ( $p != null )
 42      {
 43         $pre = $p ;
 44          if ( $node < $p -> value)
 45          {
 46              $p = $p -> left;
 47          } else {
 48              $p = $p -> right;
 49          }
 50      }
 51      / / After the loop, $pre is the parent node of $node 
52      if ( $node < $pre -> value)
 53      {
 54          $pre ->left =new tree( $node );
 55      } else {
 56          $pre ->right = new tree( $node );
 57      }
 58  }
 59  
60  // Binary search tree insertion node (recursion) 
61  function tmp_insert_node( $header , $ node )
 62  {
 63      $tmp_node = new tree( $node );
 64      if ( $header == null )
 65      {
 66         $header = $tmp_node;
67         return $header;
68     }
69     
70     if($node < $header->value)
71     {
72         $header->left = tmp_insert_node($header->left, $node);
73     } else {
74         $header->right = tmp_insert_node($header->right, $node);
75     }
76     return $header;
77 }
78 
79 $header = null;
80 add($header);//非递归
81 show($header);
82 
83 $res = tmp_insert_node($header, 5);//递归
84 show($res);
85 $res = tmp_insert_node($header, 7);
86 show($res);

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325206163&siteId=291194637