Binary search tree

1.Introduction

  • Each node in the left sub-tree of that node has a value less than or equal to the value of the node

  • Each node in the right sub-tree of that node has a value larger than or equal to the value of the node

  • Binary search tree are typically used for fast insertion and fast lookup

  • all left descendents <= n < all right descendents

2.Balanced v.s. Unbalanced

  • Balanced不一定只有左右子樹的size相同, 需再了解紅黑樹(red-black trees), AVL tree

  • 以下為balanced tree的種類

    1. Completed tree: child node先由左邊填起

    2. Full binary tree:0或2個child node

    3. Perfect tree:Completed tree + Full binary tree

3.Insertion

  • In a tree when a new code is added there is exactly one place that it can be

  • The structure of the tree depends on the order in which the nodes are added

  • The complexity for node insertion is O(Log n) in the average case

  • The actual complexity depends on the shape of the tree - skewed trees (IE. with all left or right children only) can have complexity of O(n)

  • 跟head比大小, 小-> 跟左子繼續比; 大->跟右子繼續比, 當child為NULL時insert

4.Lookup

  • While searching for a node in the tree there is only one place where that node can be found

  • We can simply follow the right or left sub-trees based on the value we want to find

  • The complexity for node lookup is O(Log n) in the average case

5.Minimum value in BST

6.Maximum depth of a binary tree

7.Mirror a binary tree

8.Finding the structurally unique trees

9.Print all nodes within a range in a binary search tree

  • L -> V -> R

10.Check if a binary search tree

11.Path sum

12.Print all paths

13.Least common ancestor

Last updated