分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > IT知识

PHP遍历二叉树

发布时间:2023-09-06 02:31责任编辑:董明明关键词:PHP遍历

遍历二叉树,这个相对比较复杂。

二叉树的便利,主要有两种,一种是广度优先遍历,一种是深度优先遍历。

什么是广度优先遍历?就是根节点进入,水平一行一行的便利。

什么是深度优先遍历呢?就是根节点进入,然后按照一个固定的规律,一直向下走,一个方向的子树遍历之后再遍历另一个方向的子树。

深度优先遍历,主要有三种顺序遍历:先序(先输出根节点),中序(第二个输出根节点),后序(最后输出根节点)。

直接上代码吧。

 1 class Node { 2 ????public $data = null; 3 ????public $left = null; 4 ????public $right = null; 5 } 6 ?7 $node1 = new Node(); 8 $node2 = new Node(); 9 $node3 = new Node();10 $node4 = new Node();11 $node5 = new Node();12 $node6 = new Node();13 $node7 = new Node();14 $node8 = new Node();15 $node9 = new Node();16 17 $node1->data = 1;18 $node2->data = 2;19 $node3->data = 3;20 $node4->data = 4;21 $node5->data = 5;22 $node6->data = 6;23 $node7->data = 7;24 $node8->data = 8;25 $node9->data = 9;26 27 $node1->left = $node2;28 $node1->right = $node3;29 $node2->left = $node4;30 $node2->right = $node5;31 $node3->left = $node6;32 $node3->right = $node7;33 $node4->left = $node8;34 $node4->right = $node9;

以上代码,简单建立一个二叉树,如下图:

广度优先遍历

 1 // 二叉树广度优先遍历 2 function binary_tree1($node) { 3 ????$result = [];//保存结果 4 ????$memc = []; 5 ????array_push($memc, $node);//根节点入队 6 ????while (!empty($memc)) {//持续输出节点,直到队列为空 7 ????????$cnode = array_shift($memc);//最前边的元素出队 8 ????????$result[] = $cnode->data;//记录当前节点的值 9 ????????//左节点先入队,然后右节点入队10 ????????if ($cnode->left != null) 11 ????????????array_push($memc, $cnode->left);12 ????????if ($cnode->right != null) 13 ????????????array_push($memc, $cnode->right);14 ????}15 ????return $result;16 }17 18 print_r(binary_tree2($node1));

深度优先遍历(先序)

 1 // 二叉树深度优先遍历(先序) 2 function binary_tree2($node) 3 { 4 ????$result = [];//结果数组 5 ????$memc ?= []; 6 ????array_push($memc, $node);//将根节点压栈 7 ????while (!empty($memc)) { 8 ????????$cnode = array_pop($memc);//弹出刚刚压栈的节点 9 ????????$result[] = $cnode->data;10 ????????//因为先进后出原则,想先显示左子树,所以先压入右子树11 ????????if ($cnode->right != null) {12 ????????????array_push($memc, $cnode->right);13 ????????}14 ????????if ($cnode->left != null) {15 ????????????array_push($memc, $cnode->left);16 ????????}17 ????}18 ????return $result;19 }20 21 print_r(binary_tree2($node1));

PHP遍历二叉树

原文地址:https://www.cnblogs.com/leafinwind/p/10306553.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved