二叉树遍历

  class Node {
        public $data;
        public $left;
        public $right;

        public function __construct($data){
            $this->data=$data;
        }
    }
    class CreateTree{
        public $tree;
        //二叉树进行插入
        public function insert($data){
            if(!$this->tree){
                $this->tree = new Node($data);
                return ;
            }
            $p = $this->tree;
            while($p){
                if($data < $p->data ){
                    if(!$p->left){
                        $p->left = new Node($data);
                        return ;
                    }
                    $p= $p->left;
                }elseif($data > $p->data){
                    if(!$p->right){
                        $p->right = new Node($data);
                        return;
                    }
                    $p=$p->right;
                }
            }
        }
        //前序遍历
        public function preOrder(){
            $stack = array();
            $root = $this->tree;
            array_push($stack,$root);
            while(!empty($stack)){
                $p = array_pop($stack);
                echo $p->data.PHP_EOL;
                if($p->right != null){
                    array_push($stack,$p->right);
                }
                if($p->left != null){
                    array_push($stack,$p->left);
                }
            }
        }
        //中序遍历
        public function inOrder(){
            $stack = array();
            $tree = $this->tree;
            while(!empty($stack) || $tree != null){
                while($tree != null){
                    array_push($stack,$tree);
                    $tree = $tree->left;
                }
                $tree = array_pop($stack);
                echo $tree->data.PHP_EOL;
                $tree=$tree->right;
            }
        }
        //后序遍历
        public function tailOrder(){
            $stack = array();
            $output = array();
            $tree = $this->tree;
            array_push($stack,$tree);
            while(!empty($stack)){
                $tree = array_pop($stack);
                array_push($output,$tree);
                if($tree->left != null){
                    array_push($stack,$tree->left);
                }
                if($tree->right != null){
                    array_push($stack,$tree->right);
                }
            }

            while(!empty($output)){
                $p = array_pop($output);
                echo $p->data.PHP_EOL;
            }
        } 
    }
    $objcreate  = new CreateTree();
    $arr = array(16,33,32,50,13,5,14);
    foreach ($arr as $key => $value) {
        $objcreate->insert($value);
    }
    //$objcreate->preOrder();#前序遍历
    //$objcreate->inOrder();#中序遍历
    //$objcreate->tailOrder();#结序遍历

  

原文地址:https://www.cnblogs.com/zh718594493/p/12093302.html