Junior — Middle
Explain the principle of operation of data structures in the form of binary trees.
sobes.tech AI
Answer from AI
A binary tree is a data structure where each node has at most two children: left and right. The main principle is that each node contains a value and references to its children, which allows organizing data and performing search, insertion, and deletion operations efficiently.
For example, in a binary search tree (BST), for each node, all values in the left subtree are less than the node's value, and in the right subtree, they are greater. This simplifies searching: compare the target value with the current node and go to the left or right subtree.
Example in PHP (simplified tree node):
class TreeNode {
public $value;
public $left = null;
public $right = null;
public function __construct($value) {
$this->value = $value;
}
}
Binary trees are widely used for organizing data, for example, in databases, indexes, and sorting.