Catalogue
Definition of Tree
- at most two children node
1 | # Definition for a binary tree node. |
Application
- Social networks analysis
- Information indexing
- Information compression
388. Longest Absolute File Path
- use Stack to simulate the traversal of file system
1 | class Solution: |
Terms
- Balanced Binary Tree
Balanced Binary Tree is commonly defined as a binary tree in which the depth of the left and right subtrees of every node differ by 1 or less - Complete Binary Tree
Complete Binary Tree is a banary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible. - Binary Search Tree
Binary Search Tree is for every sigle node in the tree, the values in its left subtree are all smaller than its value, and the values in its right subtree are all larger than its value.
919. Complete Binary Tree Inserter
Solution1. Array
- For Complete Binary Search Tree, we can use an array to save all the node index! Then we can find its parent using the index relation!
1 | class CBTInserter: |
Solution2. Deque
- Have the Same time and space complexity, but actually use half spaces than sol1!!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28class CBTInserter:
def __init__(self, root):
self.root = root
self.deque = collections.deque()
queue = collections.deque([root])
while queue:
node = queue.popleft()
if not node.left or not node.right:
self.deque.append(node)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
def insert(self, v):
node = TreeNode(v)
parent = self.deque[0]
if not parent.left:
parent.left = node
else:
parent.right = node
self.deque.popleft()
self.deque.append(node)
return parent.val
def get_root(self):
return self.root
222. Count Complete Tree Nodes
1 | class Solution: |
Follow Up
- Given the key n, binary tree key is [1, 2, 3, 4 …], how to check if the node with key n in the complete binary tree ?
Time : O(log n) - Can you count the number of nodes in complete binary tree, based on previous question?
Binary Search + Previous Question. Time ($(logn)^2$)