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;

    欢迎大家学习,交流
  • 相关阅读:
    使用air16sdk打包ipa报错
    笔试题目
    网络编程Socket之UDP
    网络编程Socket之TCP
    Spring的HelloWorld
    一起学makefile
    使用Eclipse创建Hibernate工程
    log4j日志输出使用教程
    监听tomcat服务器启动/关闭并从配置文件中读取参数进行初始化
    java加载配置文件
  • 原文地址:https://www.cnblogs.com/lijintao1025/p/8532772.html
Copyright © 2011-2022 走看看