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;

    欢迎大家学习,交流
  • 相关阅读:
    Django ListView实现分页
    redis-pipeline
    MRO
    进程状态
    ORM基本操作回顾
    协程回顾
    线程的回顾
    multiprocessing- 基于进程的并行性
    Fix Curl client hung issue
    Curl request 'Expect: 100-Continue' Issues and Risks
  • 原文地址:https://www.cnblogs.com/lijintao1025/p/8532772.html
Copyright © 2011-2022 走看看