Day20-BinaryTree07
235. Lowest Common Ancestor of a Binary Search Tree
Node:
Time Complexity && Space Complexity
- Time Complexity: O(logn)
- Best/average case (balanced BST): O(log n)
- Worst case (unbalanced BST): O(n)
- In a balanced BST, the height h is logarithmic in terms of the number of nodes n, meaning h = O(log n).
- In the worst case, if the tree is skewed (completely unbalanced), the height of the tree could be O(n) where n is the total number of nodes.
- Space Complexity: O(logn)
- Best/average case (balanced BST): O(log n)
- Worst case (unbalanced BST): O(n)
1 | var lowestCommonAncestor = function (root, p, q) { |
701. Insert into a Binary Search Tree
Node:
Time Complexity && Space Complexity
- Time Complexity: O()
- Best/average case (balanced BST): O(log n)
- Worst case (unbalanced BST): O(n)
- Space Complexity: O()
- Best/average case (balanced BST): O(log n)
- Worst case (unbalanced BST): O(n)
1 | var insertIntoBST = function (root, val) { |
450. Delete Node in a BST
Node:
- Find the smallest node, add the left subtree of the deleted node to left of the smallest node
- use root.right to replace the root to be deleted
Time Complexity && Space Complexity
Time Complexity: O()
- Best/average case (balanced BST): O(log n)
- Worst case (unbalanced BST): O(n)
- Two parts are time-consuming
- Traversing the Tree to Find the Node: O(log n)
- Finding the Smallest Node in the Right Subtree (If Necessary): O(log n)
Space Complexity: O()
- Best/average case (balanced BST): O(log n)
- Worst case (unbalanced BST): O(n)
1 | var deleteNode = function(root, key) { |
- Title: Day20-BinaryTree07
- Author: Guoyi
- Created at : 2024-10-11 13:07:03
- Updated at : 2024-12-07 03:58:41
- Link: https://guoyiwang.github.io/Algorithm/Day20-BinaryTree07/
- License: This work is licensed under CC BY-NC-SA 4.0.
Comments