tree (ประกอบกับ ordering บางอย่าง e.g., BST) สามารถเข้าถึงข้อมูลได้เร็วกว่า linear data structure
tree สามารถเพิ่มลบข้อมูลได้สะดวกกว่าในบางกรณี
tree สามารถ implement ในรูปแบบคล้ายกับ linked list ได้
Binary Tree
คือ tree ที่แต่ละ node มีลูกไม่เกินสองลูก คือ left และ right
ตัวอย่าง
Binary Tree node มีส่วนประกอบต่อไปนี้
ข้อมูล
Pointer to left child
Pointer to right child
#include<bits/stdc++.h>usingnamespace std;structNode{int data;structNode*left;structNode*right;// val is the key or the value that// has to be added to the data partNode(int val){
data = val;// Left and right child for node// will be initialized to null
left =NULL;
right =NULL;}};intmain(){/*create root*/structNode*root =newNode(1);/* following is the tree after above statement
1
/ NULL NULL
*/
root->left =newNode(2);
root->right =newNode(3);/* 2 and 3 become left and right children of 1
1
/ \
2 3
/ \ / \
NULL NULL NULL NULL
*/
root->left->left =newNode(4);/* 4 becomes left child of 2
1
/ \
2 3
/ \ / \
4 NULL NULL NULL
/ \
NULL NULL
*/return0;}
ใช้ array ในการสร้าง binary tree
ขนาดเรารู้ขนาดของ binary tree แล้วเราสามารถใช้ array ได้