zoukankan      html  css  js  c++  java
  • php实现二叉树

    <?php

    class tree{
    public $key;
    public $left;
    public $right;

    public function __construct($key){
    $this->key = $key;
    }

    /**
    * 先序遍历
    */
    public function travers_pre_order(){
    $l = array();
    $r = array();

    if($this->left){
    $l = $this->left->travers_pre_order();
    }

    if($this->right){
    $r = $this->right->travers_pre_order();
    }
    return array_merge(array($this->key),$l,$r);
    }

    /**
    * 中序遍历
    */
    public function travers_in_order(){
    $l = array();
    $r = array();
    if($this->left){
    $l = $this->left->travers_in_order();
    }

    if($this->right){
    $r = $this->right->travers_in_order();
    }

    return array_merge($l,array($this->key),$r);
    }

    /**
    * 后序遍历
    */
    public function travers_post_order(){
    $l = array();
    $r = array();

    if($this->left){
    $l = $this->left->travers_post_order();
    }

    if($this->right){
    $r = $this->right->travers_post_order();
    }

    return array_merge($l,$r,array($this->key));
    }


    }


    $root = new tree('a');

    $root->left = new tree('b');
    $root->left->left = new tree('c');
    $root->left->left->left = new tree('d');
    $root->left->right = new tree('e');
    $root->right = new tree('f');

    var_dump($root->travers_in_order());exit;

    欢迎大家学习,交流
  • 相关阅读:
    页面的三大家族
    封装函数
    图片自动播放的案例
    动画封装
    长图滚动案例+点名册案例
    时钟案例
    伪随机数,随机数种子seed
    numpy.tolist( )函数
    countif( ) 函数判断当前单元格的身份证号码是否重复出现
    Excel技巧
  • 原文地址:https://www.cnblogs.com/lijintao1025/p/8532772.html
Copyright © 2011-2022 走看看