畫江湖之資料結構【第三話:二叉樹】二茶?

Krisji發表於2019-03-20

1 二叉樹簡介

概括:

  • 二叉樹是每個結點最多有兩個子樹的樹結構
    file
  • 二叉樹的遍歷
  • 二叉樹遍歷的定義:按照一定的規律不重複地訪問(或取出結點中的資訊,或對結點作其它的處理)二叉樹中的每一個結點。

    1. 先序遍歷(DLR) 根左右 preOrder
    2. 中序遍歷(LDR) 左根右 inOrder
    3. 後序遍歷(LRD) 左右根 postOrder

2 以下介紹上述三種遍歷二叉樹的簡介

DLR(先序遍歷)、LDR(中序遍歷)、LRD(後序遍歷)

1. 先序遍歷結果為: 8 3 1 6 4 7 10 14 13

2. 中序遍歷結果為: 1 3 4 6 7 8 10 13 14

3. 後序遍歷結果為: 1 4 7 6 3 13 14 10 8

file

完整程式碼塊

<?php 

//
//                   8
//                 /   \
//                3     10
//               / \      \
//              1   6      14
//                 / \     /
//                4   7   13 
//

class tree{
    public $data;
    public $left =  null ;
    public $right = null;
    public function __construct($data){
        $this->data = $data;
    }

    // DLR
    public function preOrder(){
        echo $this->data." ";
        if($this->left)
            $this->left->preOrder();
        if($this->right)
            $this->right->preOrder();
    }
    // LDR
    public function inOrder(){
        if($this->left)
            $this->left->inOrder();
        echo $this->data." ";
        if($this->right)
            $this->right->inOrder();
    }
    // LRD
    public function postOrder(){
        if($this->left)
            $this->left->postOrder();
        if($this->right)
            $this->right->postOrder();
        echo $this->data." ";
    }
}

$trees = new tree(8);
$trees->left =  new tree(3);
$trees->left->left =  new tree(1);
$trees->left->right = new tree(6);
$trees->left->right->left = new tree(4);
$trees->left->right->right = new tree(7);

$trees->right =  new tree(10);
$trees->right->right = new tree(14);
$trees->right->right->left =  new tree(13);

echo "<pre>";
$trees->preOrder();
echo "<br>";
$trees->inOrder();
echo "<br>";
$trees->postOrder();
echo "<br>";

3 分析程式碼塊 具體分析到程式碼註釋哦 ~

先定義樹的結構屬性

class tree{
    public $data;
    public $left =  null ;
    public $right = null;
    public function __construct($data){
        $this->data = $data;
    }

先序遍歷 (順序為根左右)

// DLR 先序遍歷(根左右)
    public function preOrder(){
        echo $this->data." ";//先輸出根節點 8 3 1
        if($this->left)//如果這個根節點有左子樹
            $this->left->preOrder();//遞迴輸出左子樹 3 4
        if($this->right)//如果這個子節點有右子樹 3
            $this->right->preOrder();//遞迴輸出右子樹 6 7

    }
    $trees->preOrder();

中序遍歷 (順序為左根右)

// LDR 中序遍歷(左根右)
public function inOrder(){
if($this->left)//先遞迴遍歷左邊的樹
$this->left->inOrder();
echo $this->data." ";//輸出中間的樹
if($this->right)//再遞迴遍歷右邊的樹
$this->right->inOrder();
}

後序遍歷 (順序為左右根)

// LRD 後序遍歷(左右根)
public function postOrder(){
if($this->left)//先遞迴遍歷左邊的樹
$this->left->postOrder();
if($this->right)//再遞迴遍歷右邊的樹
$this->right->postOrder();
echo $this->data." ";//最後輸出根
}

相關文章