当前位置:首页 > PHP教程 > php应用 > 列表

PHP实现二叉树的深度优先与广度优先遍历方法

发布:smiling 来源: PHP粉丝网  添加日期:2021-06-19 20:51:43 浏览: 评论:0 

这篇文章主要介绍了PHP实现二叉树的深度优先与广度优先遍历方法,涉及php针对二叉树进行遍历的相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下。

本文实例讲述了PHP实现二叉树的深度优先与广度优先遍历方法,分享给大家供大家参考,具体如下:

  1. #二叉树的广度优先遍历 
  2. #使用一个队列实现 
  3. class Node { 
  4.  public $data = null; 
  5.  public $left = null; 
  6.  public $right = null; 
  7. } 
  8. #@param $btree 二叉树根节点 
  9. function breadth_first_traverse($btree) { 
  10.  $traverse_data = array(); 
  11.  $queue = array(); 
  12.  array_unshift($queue, $btree); #根节点入队 
  13.  while (!emptyempty($queue)) { #持续输出节点,直到队列为空 
  14.    $cnode = array_pop($queue); #队尾元素出队 
  15.    $traverse_data[] = $cnode->data; 
  16.    #左节点先入队,然后右节点入队 
  17.    if ($cnode->left != null) array_unshift($queue, $cnode->left); 
  18.    if ($cnode->right != null) array_unshift($queue, $cnode->right); 
  19.  } 
  20.  return $traverse_data; 
  21. } 
  22. #深度优先遍历,使用一个栈实现 
  23. function depth_first_traverse($btree) { 
  24. $traverse_data = array(); 
  25. $stack = array(); 
  26. array_push($stack, $btree); 
  27. while (!emptyempty($stack)) { 
  28.   $cnode = array_pop($stack); 
  29.   $traverse_data[] = $cnode->data; 
  30.   if ($cnode->right != null) array_push($stack, $cnode->right); 
  31.   if ($cnode->left != null) array_push($stack, $cnode->left); 
  32. } 
  33. return $traverse_data; 
  34. } 
  35. $root = new Node(); 
  36. $node1 = new Node(); 
  37. $node2 = new Node(); 
  38. $node3 = new Node(); 
  39. $node4 = new Node(); 
  40. $node5 = new Node(); 
  41. $node6 = new Node(); 
  42. $root->data = 1; 
  43. $node1->data = 2; 
  44. $node2->data = 3; 
  45. $node3->data = 4; 
  46. $node4->data = 5; 
  47. $node5->data = 6; 
  48. $node6->data = 7; 
  49. $root->left = $node1; 
  50. $root->right = $node2; 
  51. $node1->left = $node3; 
  52. $node1->right = $node4; 
  53. $node2->left = $node5; 
  54. $node2->right = $node6; 
  55. $traverse = breadth_first_traverse($root); 
  56. print_r($traverse); 
  57. echo ""; 
  58. $traverse = depth_first_traverse($root); 
  59. print_r($traverse);

Tags: PHP二叉树 PHP遍历

分享到: