> For the complete documentation index, see [llms.txt](https://garychang.gitbook.io/data-structure/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://garychang.gitbook.io/data-structure/lecture2-tree-and-binary-tree/lecture2.2-binary-tree.md).

# 2.2 - Binary Tree

介紹Binary Tree的定義、基本定理及表示方法

### 1. 定義

1. 可以為空(node=0)，若不為空則必須有Root及左右子樹
2. 左右子樹必須為Binary Tree
3. 左右子樹有方向之別

### 2. 基本定理及證明

#### 2.1 在Binary Tree中，第 $$i$$ level中最多 $$2^{i-1}$$ 有個nodes

數學歸納法：

1. for level = 1, $$2^{1-1}=1$$個nodes
2. if level = n-1 holds, show that level = n also holds
3. for level =n , nodes of n = 2\*nodes of n-1 $$2\*2^{(i-1)-1} = 2^{i-1}$$&#x20;

#### 2.2 高度 $$k$$ 的Binary Tree，最多nodes數為 $$2^k-1$$ ；最少nodes數為 $$k$$&#x20;

$$
2^{0}+2^{1}+...+2^{k-1}+2^{k} = \frac{2^{k}-2^{0}}{2-1}=2^{k}-1
$$

#### 2.3 在一個非空二元樹，若degree為０的nodes數(leaf)有 $$n\_{0}$$ ，degree為2的nodes數有 $$n\_{2}$$ ，則 $$n\_{0}=n\_{2}+1$$&#x20;

假設： $$n$$ 為nodes總數 $$n = n\_{0}+n\_{1}+n\_{2}$$

&#x20;            $$n\_{1}$$為degree=1的nodes數

&#x20;            $$B$$為branches總數(links) $$B = 0n\_{0}+1n\_{1}+2n\_{2}$$&#x20;

$$
n =B+1,\newline
\implies n\_{0}+n\_{1}+n\_{2}=1n\_{1}+2n\_{2}+1\newline
\implies n\_{0} = n\_{2}+1
$$

### 3. 種類

* Skewed Binary Tree

可分為：left-skewed及right-skewed binary tree

```
left                       right
    O                      O
   /                        \
  O                          O
 /                            \
O                              O
```

* Full Binary Tree

擁有最多節點數的Binary Tree( $$2^{k}-1$$ )

* Complete Binary Tree

1. 高度為k且擁有n個節點，且滿足 $$2^{k-1}-1\<n≤2^{k}-1$$&#x20;
2. 節點編號與高度為k的Full Binary Tree的前n個節點編號一一對應

```
即：
         1
        / \
       2   3
      / \ / \
     4  5 6  7
    / \ /
   8  910
```

&#x20;若complete binary tree的某個節點編號為i，則i的

1. 左子點編號為 $$2i$$ ，若 $$2i>n$$ 則無左子點
2. 右子點編號為 $$2i+1$$ ，若 $$2i+1>n$$ 則無右子點
3. 父點編號為 $$\[\frac{i}{2}]$$ ，若 $$\[\frac{i}{2}]<1$$ 則無父點

* Strict Binary Tree

Binary Tree中每個non-leaf節點必有兩個子點，即 $$n\_{1}=0$$&#x20;

### 4. 表示方法

#### 4.1 使用Array儲存

按照full binary tree的節點編號儲存到對應的矩陣indice中

* 優點：
  * 容易存取左右子點及父點
  * 對於full/complete binary tree沒有儲存空間浪費
* 缺點：
  * 節點增減較麻煩
  * 對於skewed binary tree非常浪費空間

#### 4.2 使用Linklist儲存

\[point to left child]\[data]\[point to right child]

* 優點：
  * 節點增減容易
  * 對於skewed binary tree相較於array節省空間
* 缺點：
  * 不易存取父點
  * links空間浪費約50%
