A binary tree is a hierarchical data structure where every node holds a value and has at most two children, conventionally called left and right. The top node is the root, and nodes with no children are leaves.
Why it matters
Trees model hierarchical data and enable fast searching. In a binary search tree (BST), values in the left subtree are smaller than the node and values in the right subtree are larger, so each comparison discards about half the remaining nodes, giving O(log n) lookup when the tree is balanced. If values are inserted in sorted order, a plain BST degenerates into a linked list with O(n) operations, which is why balanced variants such as AVL and red-black trees exist. Heaps, expression parsers and many database indexes (B-trees, a multiway relative) build on tree ideas.
Example
class Node:
def __init__(self, v): self.v, self.l, self.r = v, None, None
def contains(node, x):
if node is None: return False
if x == node.v: return True
return contains(node.l if x < node.v else node.r, x)
Common mistakes
- Assuming a BST is always balanced.
- Recursing on very deep trees and overflowing the stack.
- Confusing a binary tree with a binary search tree, which has an ordering rule.
Related
Get notified when this term updates
Plus occasional practical tips on uptime and monitoring, nothing else. Unsubscribe anytime.
यह पेज सामान्य जानकारी है, जिसे हमारी संपादकीय टीम ने लिखा है और दस्तावेज़ीकरण बदलने पर अपडेट किया जाता है। सर्वर और प्रदाता अलग-अलग होते हैं, इसलिए बदलाव पहले सुरक्षित तरीके से जाँचें। देखें: संपादकीय नीति और अस्वीकरण.