12-bo'lim: Daraxtlar (Binary Tree / BST)¶
π³ BST (binary search tree): chap bola har doim kichikroq, o'ng bola kattaroq. Funksiyalar 135-masaladagi
TreeNodeklassidan foydalanadi. Murakkablikdagihβ balandlik: muvozanatli daraxtda O(log n), qiyshiq daraxtda O(n).
135. TreeNode (class) + BST'ga qo'shish¶
β± o'rtacha O(log n), eng yomon O(n) Β· πΎ O(h)
JS
class TreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
const insert = (root, value) => {
if (!root) return new TreeNode(value);
if (value < root.value) root.left = insert(root.left, value);
else root.right = insert(root.right, value);
return root;
};
class TreeNode {
public ?TreeNode $left = null;
public ?TreeNode $right = null;
public function __construct(public mixed $value) {}
}
function insert(?TreeNode $root, $value): TreeNode {
if ($root === null) return new TreeNode($value);
if ($value < $root->value) $root->left = insert($root->left, $value);
else $root->right = insert($root->right, $value);
return $root;
}
class TreeNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert(root, value):
if root is None:
return TreeNode(value)
if value < root.value:
root.left = insert(root.left, value)
else:
root.right = insert(root.right, value)
return root
136. BST'da qidirish¶
β± o'rtacha O(log n), eng yomon O(n) Β· πΎ O(1) (iterativ)
JS
const search = (root, value) => {
while (root) {
if (value === root.value) return true;
root = value < root.value ? root.left : root.right;
}
return false;
};
function search(?TreeNode $root, $value): bool {
while ($root !== null) {
if ($value === $root->value) return true;
$root = $value < $root->value ? $root->left : $root->right;
}
return false;
}
def search(root, value):
while root:
if value == root.value:
return True
root = root.left if value < root.value else root.right
return False
137. Inorder traversal (chap β root β o'ng)¶
β± O(n) Β· πΎ O(h)
BST'da inorder saralangan tartibni beradi.
JS
const inorder = root => {
const out = [];
const walk = node => {
if (!node) return;
walk(node.left);
out.push(node.value);
walk(node.right);
};
walk(root);
return out;
};
function inorder(?TreeNode $root): array {
$out = [];
$walk = function (?TreeNode $node) use (&$walk, &$out) {
if ($node === null) return;
$walk($node->left);
$out[] = $node->value;
$walk($node->right);
};
$walk($root);
return $out;
}
def inorder(root):
out = []
def walk(node):
if node is None:
return
walk(node.left)
out.append(node.value)
walk(node.right)
walk(root)
return out
Quyidagi BST'da inorder tartib (chap β root β o'ng) qanday qilib saralangan natija berishini ko'ring:
138. Preorder traversal (root β chap β o'ng)¶
β± O(n) Β· πΎ O(h)
Root birinchi β daraxtni nusxalash/serializatsiya uchun qulay.
JS
const preorder = root => {
const out = [];
const walk = node => {
if (!node) return;
out.push(node.value);
walk(node.left);
walk(node.right);
};
walk(root);
return out;
};
function preorder(?TreeNode $root): array {
$out = [];
$walk = function (?TreeNode $node) use (&$walk, &$out) {
if ($node === null) return;
$out[] = $node->value;
$walk($node->left);
$walk($node->right);
};
$walk($root);
return $out;
}
def preorder(root):
out = []
def walk(node):
if node is None:
return
out.append(node.value)
walk(node.left)
walk(node.right)
walk(root)
return out
139. Postorder traversal (chap β o'ng β root)¶
β± O(n) Β· πΎ O(h)
Bolalar birinchi β daraxtni o'chirish/bo'shatish uchun qulay.
JS
const postorder = root => {
const out = [];
const walk = node => {
if (!node) return;
walk(node.left);
walk(node.right);
out.push(node.value);
};
walk(root);
return out;
};
function postorder(?TreeNode $root): array {
$out = [];
$walk = function (?TreeNode $node) use (&$walk, &$out) {
if ($node === null) return;
$walk($node->left);
$walk($node->right);
$out[] = $node->value;
};
$walk($root);
return $out;
}
def postorder(root):
out = []
def walk(node):
if node is None:
return
walk(node.left)
walk(node.right)
out.append(node.value)
walk(root)
return out
140. Level-order traversal (BFS)¶
β± O(n) Β· πΎ O(n)
Kenglik bo'yicha β navbat (queue) ishlatiladi, rekursiv traversal'lardan farqli.
JS
const levelOrder = root => {
if (!root) return [];
const out = [], queue = [root];
let i = 0;
while (i < queue.length) {
const node = queue[i++];
out.push(node.value);
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
return out;
};
function levelOrder(?TreeNode $root): array {
if ($root === null) return [];
$out = [];
$queue = [$root];
$i = 0;
while ($i < count($queue)) {
$node = $queue[$i++];
$out[] = $node->value;
if ($node->left !== null) $queue[] = $node->left;
if ($node->right !== null) $queue[] = $node->right;
}
return $out;
}
from collections import deque
def level_order(root):
if root is None:
return []
out = []
queue = deque([root])
while queue:
node = queue.popleft()
out.append(node.value)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return out
Diagrammada navbat yordamida daraxt qatlam-qatlam (yuqoridan pastga) qanday kezilishi tasvirlangan:
141. Daraxt balandligi (height / max depth)¶
β± O(n) Β· πΎ O(h)
JS
PHPfunction height(?TreeNode $root): int {
return $root === null ? 0 : 1 + max(height($root->left), height($root->right));
}
142. Tugunlar sonini sanash¶
β± O(n) Β· πΎ O(h)
JS
PHPfunction countNodes(?TreeNode $root): int {
return $root === null ? 0 : 1 + countNodes($root->left) + countNodes($root->right);
}
def count_nodes(root):
return 0 if root is None else 1 + count_nodes(root.left) + count_nodes(root.right)
143. BST'ni tekshirish (validate BST)¶
β± O(n) Β· πΎ O(h)
Har node uchun ruxsat etilgan (min, max) oraliq uzatiladi β faqat to'g'ridan-to'g'ri ota emas, butun ajdodlar bilan moslik tekshiriladi.
JS
const isValidBST = (root, min = -Infinity, max = Infinity) => {
if (!root) return true;
if (root.value <= min || root.value >= max) return false;
return isValidBST(root.left, min, root.value) && isValidBST(root.right, root.value, max);
};
function isValidBST(?TreeNode $root, float $min = -INF, float $max = INF): bool {
if ($root === null) return true;
if ($root->value <= $min || $root->value >= $max) return false;
return isValidBST($root->left, $min, $root->value)
&& isValidBST($root->right, $root->value, $max);
}
def is_valid_bst(root, low=float("-inf"), high=float("inf")):
if root is None:
return True
if not (low < root.value < high):
return False
return is_valid_bst(root.left, low, root.value) and is_valid_bst(root.right, root.value, high)
144. Daraxtni aks ettirish (invert / mirror)¶
β± O(n) Β· πΎ O(h)
JS
const invert = root => {
if (!root) return null;
[root.left, root.right] = [invert(root.right), invert(root.left)];
return root;
};
function invert(?TreeNode $root): ?TreeNode {
if ($root === null) return null;
[$root->left, $root->right] = [invert($root->right), invert($root->left)];
return $root;
}
def invert(root):
if root is None:
return None
root.left, root.right = invert(root.right), invert(root.left)
return root
145. Eng kichik umumiy ajdod (LCA, BST)¶
β± O(h) Β· πΎ O(1)
BST xossasidan foydalanib β ikki qiymat bo'linadigan birinchi node LCA bo'ladi.
JS
const lca = (root, p, q) => {
while (root) {
if (p < root.value && q < root.value) root = root.left;
else if (p > root.value && q > root.value) root = root.right;
else return root.value;
}
return null;
};
function lca(?TreeNode $root, $p, $q) {
while ($root !== null) {
if ($p < $root->value && $q < $root->value) $root = $root->left;
elseif ($p > $root->value && $q > $root->value) $root = $root->right;
else return $root->value;
}
return null;
}
def lca(root, p, q):
while root:
if p < root.value and q < root.value:
root = root.left
elif p > root.value and q > root.value:
root = root.right
else:
return root.value
return None