Tree

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 13

BSTTopic/Course

- Sum
Sub-Topic (Example: name of college)
Key idea
• Initialize the first element as root

• Next check the element -> Insertion

1. Data < root -> store it as left child


2. Data > root -> store it as right child

• Traverse the element -> sum

1. root
2. root -> left
3. Root -> right

• Print the sum


Key idea
Input: 6 3 1 4 2 6

Sum of all nodes are 16


3

Sum 9
8
6
16
13
1 4

2
BSTTopic/Course
- Diameter
Sub-Topic (Example: name of college)
Key idea
• Initialize the first element as root

• Next check the element -> Insertion

1. Data < root -> store it as left child


2. Data > root -> store it as right child

• The diameter of a tree T is the largest of the following quantities:

1. The diameter of T’s left subtree


2. The diameter of T’s right subtree
3. The longest path between leaves that goes through the root of T (this can be computed from the
heights of the subtrees of T)
Key idea 1

Input: 1 2 3 4 5
2

Diameter of the given binary tree is 5


3

5
BSTTopic/Course
Sub-Topic (Example: name of college)

Lowest Common Ancestor


Key idea
• Initialize the first element as root

• Next check the element -> Insertion

1. Data < root -> store it as left child


2. Data > root -> store it as right child

1. Create a recursive function that takes a node and the two values n1 & n2
2. If (current node <= n1 & n2), LCA lies in the right subtree
3. Call the recursive function -> right subtree
4. If (current node >= n1 and n2), LCA lies in the left subtree
5. Call the recursive function -> left subtree
6. If both the above cases are false, then return the current node as LCA
Key idea
Input:Ancestor
Common 6 3 1 4 2(3, 6) 6

Output: 6
3

1 4

2
BSTTopic/Course
- Kth Smallest Element
Sub-Topic (Example: name of college)
Key idea
• Initialize the first element as root
• Next check the element -> Insertion up to ‘-1’

1. Data < root -> store it as left child


2. Data > root -> store it as right child

• Scan the element ‘kth value’

• Inorder Traversal of a BST traverses the nodes in increasing order

• While traversing, keep track of the count of nodes visited

• If the count becomes k, print the node


Key idea
Input
50
Left -> Root -> Right
Output: 50 50
30
20
Kth value:
40 4 30 70

70
60 20 40 60 80
80

You might also like