多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
### 基本概念 * 深度优先遍历: 对每一个可能的分支路径深入到不能再深入为止,而且每个结点只能访问一次。要特别注意的是,二叉树的深度优先遍历比较特殊,可以细分为先序遍历、中序遍历、后序遍历。具体说明如下: 前序遍历:根节点->左子树->右子树 中序遍历:左子树->根节点->右子树 后序遍历:左子树->右子树->根节点 * 广度优先遍历: 又叫层次遍历,从上往下对每一层依次访问,在每一层中,从左往右(也可以从右往左)访问结点,访问完一层就进入下一层,直到没有结点可以访问为止。 ### 动画演示 --- **此小结主要讲解深度遍历,例如有序列:A B C D E F G H K,然后各种遍历后得出结果如下所示:** * 前序遍历:A B C D E F G H K :-: ![](https://box.kancloud.cn/711963e6f586b0b5fdec71e6408a72e2_1329x901.gif =580x300) * 中序遍历:B D C A E H G K F :-: ![](https://box.kancloud.cn/e91d7c63a56eac59cbc691c242571374_1335x906.gif =600x300) * 后序遍历:D C B H K G F E A :-: ![](https://box.kancloud.cn/23e7e25cb41d5411d92d5844592970c3_1335x906.gif =600x300) ### 应用场景 (略) ### 代码示例 * 前序遍历 ``` /** * 前序遍历(递归方法) */ private function preOrder($root) { if (!is_null($root)) { $function = __FUNCTION__; echo $root->key . " "; $this->$function($root->left); $this->$function($root->right); } } ``` * 中序遍历 ``` /** * 中序遍历(递归方法) */ private function midOrder($root) { if (!is_null($root)) { $function = __FUNCTION__; $this->$function($root->left); echo $root->key . " "; $this->$function($root->right); } } ``` * 后序遍历 ``` /** * 后序遍历(递归方法) */ private function postOrder($root) { if (!is_null($root)) { $function = __FUNCTION__; $this->$function($root->left); $this->$function($root->right); echo $root->key . " "; } } ``` * 客户端调用 ``` class Client { public static function Main() { $arr = array(10, 8, 12, 7, 9, 11, 13); $tree = new Bst(); $tree->init($arr); $traverse = new traverse($tree); $traverse->preOrder(); $traverse->midOrder(); $traverse->postOrder(); } } CLient::Main(); ``` ### 小结