zoukankan      html  css  js  c++  java
  • 二叉树

    <?php
    //二叉树的遍历
    class Node{
    public $value;
    public $left;
    public $right;
    }
    //先序遍历 根节点 --->左节点 --->右节点
    function preorder ($root) {
    $stack = array();
    array_push($stack,$root);
    while(!empty($stack)) {
    $center_node = array_pop($stack); //数组的压入与弹出是以栈道的形式表现的先进后出
    echo $center_node->value.' ';
    if (!empty($center_node->right)) {
    array_push($stack, $center_node->right);
    }
    if (!empty($center_node->left)) {
    array_push($stack, $center_node->left);
    }
    }
    }
    //中序遍历 左节点--->根节点--->右节点
    function inorder ($root) {
    $stack = array();
    $center_node = $root;
    while (!empty($stack) || $center_node != null) {
    while ($center_node != null) {
    array_push($stack,$center_node);
    $center_node = $center_node->left;
    }
    $center_node = array_pop($stack);
    echo $center_node->value;
    $center_node = $center_node->right;
    }
    }
    //后序遍历 左节点--->右节点--->根节点
    function tailorder ($root) {
    $stack = array();
    $outstack = array();
    array_push($stack, $root);
    while ($stack != null) {
    $center_node = array_pop($stack);
    array_push($outstack, $center_node); //先压入根节点
    if ($center_node->left != null) {
    array_push($stack, $center_node->left);
    }
    if ($center_node->right != null) {
    array_push($stack,$center_node->right);
    }
    }
    while (!empty($outstack)) {
    $center_node = array_pop($outstack);
    echo $center_node->value;
    }
    }
    $a=new Node();
    $b=new Node();
    $c=new Node();
    $d=new Node();
    $e=new Node();
    $f=new Node();
    $a->value = 'A';
    $b->value = 'B';
    $c->value = 'C';
    $d->value = 'D';
    $e->value = 'E';
    $f->value = 'F';
    $a->left = $b;
    $a->right = $c;
    $b->left = $d;
    $c->left = $e;
    $c->right = $f;
    tailorder($a);
    ?>

  • 相关阅读:
    如何学好编程
    进制转换
    第五周学习总结 20201204 于瀛鹏
    xor运算
    20201204 于瀛鹏 第四周学习总结
    20201204 于瀛鹏 第三周学习总结
    IEEE754浮点数
    base64编码
    罗马数字(1-3999)转阿拉伯数字
    俄罗斯方块
  • 原文地址:https://www.cnblogs.com/jasonxiaoqinde/p/6690126.html
Copyright © 2011-2022 走看看