php實現二叉樹的創建以及前序/中序/後序遍歷

<?php 
class TreeNode
{
    public $val = null;
    public $left = null;
    public $right = null;

    function __construct($value)
    {
        $this->val = $value;
    }
}

class BinaryTree
{
    private $arr, $len;

    public function createTree($arr)
    {
        $this->arr = (array)$arr;
        $this->len = count($this->arr);
        $root = new TreeNode($this->arr[0]);    //數組第一個爲根結點
        $root->left = $this->generate(1);       //根據數組下標進行構建二叉樹
        $root->right = $this->generate(2);
        return $root;                           //返回根結點
    }

    /**
     * 構建二叉樹遞歸函數
     */
    private function generate($index)
    {
        if ($this->arr[$index] == '#') {          //爲#則構建節點後直接返回
            $node = new TreeNode(null);
            return $node;
        }
        $node = new TreeNode($this->arr[$index]); //有值則按照具體值構建子節點
        $key = $index * 2 + 1;                    //二叉樹在數組上的顯示是2倍跳着的
        if ($key < $this->len) {                  //防止數組越界
            $node->left = $this->generate($key++);
        }
        if ($key < $this->len) {
            $node->right = $this->generate($key);
        }
        return $node;
    }

    /**
     * 前序遍歷
     */
    public function getTree($root)
    {
        if ($root) {
            echo $root->val;
            $this->getTree($root->left);
            $this->getTree($root->right);
        }
    }
}

$tree = new BinaryTree();
$arr = [1, 2, 3, 4, '#', 5, '#', 6, 7, '#', '#', 8, 9];
$root = $tree->createTree($arr);
function preOrder($root){
	$stack = array();
	array_push($stack, $root);
	while (!empty($stack)) {
		$centerNode = array_pop($stack);
		echo $centerNode->val;
		if (!is_null($centerNode->right)) {
			array_push($stack, $centerNode->right);
		}
		if (!is_null($centerNode->left)) {
			array_push($stack, $centerNode->left);
		}
	}
}
function inOrder($root) {
	$stack = array();
	$centerNode = $root;
	while (!empty($stack) || !is_null($centerNode)) {
		while (!is_null($centerNode)) {
			array_push($stack, $centerNode);
			$centerNode = $centerNode->left;
		}
		$centerNode = array_pop($stack);
		echo $centerNode->val;
		$centerNode = $centerNode->right;
	}
}
function tailOrder($root){
	$stack = $outstack = array();
	array_push($stack, $root);
	while (!empty($stack) || !is_null($centerNode)) {
		$centerNode = array_pop($stack);
		array_push($outstack, $centerNode);
		if (!is_null($centerNode->left)) {
			array_push($stack, $centerNode->left);
		}
		if (!is_null($centerNode->right)) {
			array_push($stack, $centerNode->right);
		}

	}
	while (!empty($outstack)) {
		$centerNode = array_pop($outstack);
		echo $centerNode->val;
	}
}
// tailOrder($root);

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章