Advertisement
Guest User

Untitled

a guest
Feb 23rd, 2019
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 KB | None | 0 0
  1. class bTreeNode
  2. {
  3. private $value;
  4. public $left;
  5. public $right;
  6.  
  7. function __construct($value, $left=null, $right=null) {
  8. $this->value = $value;
  9. $this->left = $left;
  10. $this->right = $right;
  11. }
  12.  
  13. function getValue() {
  14. return $this->value;
  15. }
  16. }
  17.  
  18. function depthFirstSearch($bTree, $value) {
  19. if (is_null($bTree)) {
  20. return null;
  21. }
  22. if ($bTree->getValue() === $value) {
  23. return $bTree;
  24. }
  25. $node = depthFirstSearch($bTree->left, $value);
  26. if ($node) {
  27. return $node;
  28. }
  29. return depthFirstSearch($bTree->right, $value);
  30. }
  31.  
  32. function breadthFirstSearch($bTree, $value) {
  33. if (!$bTree) return null;
  34. $toSearch = [$bTree];
  35. while (count($toSearch)) {
  36. $node = array_shift($toSearch);
  37. if ($node->getValue() === $value) {
  38. return $node;
  39. }
  40. if ($node->left) {
  41. $toSearch[] = $node->left;
  42. }
  43. if ($node->right) {
  44. $toSearch[] = $node->right;
  45. }
  46. }
  47. return null;
  48. }
  49.  
  50. # Testing bTree
  51. $tree = new bTreeNode(50,
  52. new bTreeNode(25,
  53. new bTreeNode(12),
  54. new bTreeNode(40)
  55. ),
  56. new bTreeNode(75,
  57. new bTreeNode(60),
  58. new bTreeNode(80)
  59. )
  60. );
  61.  
  62. print($tree->getValue().PHP_EOL);
  63.  
  64. # Depth First Search
  65. $node = depthFirstSearch($tree, 5);
  66. if ($node) {
  67. print($node->getValue().PHP_EOL);
  68. }
  69. else {
  70. print("No value found" . PHP_EOL);
  71. }
  72.  
  73. $node = depthFirstSearch($tree, 12);
  74. if ($node) {
  75. print($node->getValue().PHP_EOL);
  76. }
  77. else {
  78. print("No value found" . PHP_EOL);
  79. }
  80.  
  81. # Breadth First Search
  82. $node = breadthFirstSearch($tree, 5);
  83. if ($node) {
  84. print($node->getValue().PHP_EOL);
  85. }
  86. else {
  87. print("No value found" . PHP_EOL);
  88. }
  89.  
  90. $node = breadthFirstSearch($tree, 12);
  91. if ($node) {
  92. print($node->getValue().PHP_EOL);
  93. }
  94. else {
  95. print("No value found" . PHP_EOL);
  96. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement