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;

    欢迎大家学习,交流
  • 相关阅读:
    C# 线程间互相通信
    COM组件的使用方法
    C++基于ATL工程编写ActiveX控件步骤
    VC++编写ActiveX控件
    C#协作试取消线程
    Asp.net的内置对象!!!
    C#的三大特性
    类的静态方法。。。。。
    页面的生命周期
    .net面试题 2016
  • 原文地址:https://www.cnblogs.com/lijintao1025/p/8532772.html
Copyright © 2011-2022 走看看