Binary search tree in Python
Intro
Binary Search Tree is a binary tree data structure which has the following properties:
- The left subtree of a node contains only nodes with values smaller than the node.
- The right subtree of a node contains only nodes with values greater than the node.
- The left and right subtree each must also be a binary search tree.
Based on the properties, we can implement a algorithm to check if a binary tree is binary search tree.
1 | import sys |
[Leetcode 108] Convert Sorted Array to Binary Search Tree
Given an integer array nums where the elements are sorted in ascending order, convert it to a
height-balanced binary search tree.
Example 1:
1 | 0 |
Example 2:
1 | 3 1 |
Constraints:
- 1 <= nums.length <= 10^4
- -10^4 <= nums[i] <= 10^4
- nums is sorted in a strictly increasing order.
Solution:
1 | # Definition for a binary tree node. |
[Leetcode 173] Binary Search Tree Iterator
Implement the BSTIterator class that represents an iterator over the in-order traversal of a binary search tree (BST):
- BSTIterator(TreeNode root) Initializes an object of the BSTIterator class. The root of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST.
- boolean hasNext() Returns true if there exists a number in the traversal to the right of the pointer, otherwise returns false.
- int next() Moves the pointer to the right, then returns the number at the pointer.
Notice that by initializing the pointer to a non-existent smallest number, the first call to next() will return the smallest element in the BST.
You may assume that next() calls will always be valid. That is, there will be at least a next number in the in-order traversal when next() is called.
Example 1:
1 | 3 |
Constraints:
- The number of nodes in the tree is in the range [1, 10^5].
- 0 <= Node.val <= 10^6
- At most 10^5 calls will be made to hasNext, and next.
Follow up:
- Could you implement next() and hasNext() to run in average O(1) time and use O(h) memory, where h is the height of the tree?
1 | # Definition for a binary tree node. |
[Leetcode 230] Kth Smallest Element in a BST
Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree.
Example 1:
1 | 3 |
Constraints:
- The number of nodes in the tree is n.
- 1 <= k <= n <= 104
- 0 <= Node.val <= 104
Follow up: If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?
Solution:
1 | # Definition for a binary tree node. |