31. Binary Trees-1 (traversals)
Intro-
It is a hierarchical data structure.
Binary means a node has max 2 children
Types of nodes- root node, child node, leaf node
Sub tree- the current node and all nodes beneath it together form a subtree
Ancestors- all parent nodes above current node in its branch
---------------------------------------------------------------------------------------------------------------
Types of trees-
1. Balanced BT:- left & right subtree's height differ by at most 1, ( height ~ log₂ n )
- Perfect BT:- all internal nodes have 2 children & all leaf nodes are at same level.
- Complete BT:- all levels except last are completely filled & last level has all nodes as left as possible
2. Degenerate tree- all nodes have 1 child only
- Skewed Trees- special trees where all nodes lean on one side (height ~ n)
3. Full BT:- every node has 0 or 2 children
---------------------------------------------------------------------------------------------------------------
Representation:-
a struct with 2 pointers (left & right) and a value
in trees we need root node
Traversals-
1.BFS✅ time- O(n) ; space- O(n)-----------------------------------------------
2. iterative DFS using 1 stack🔥 time-O(n) ; space- O(n) (H, for in-order)
--------------------------------------------------
# iterative DFS (post order) using 2 stacks⭐ time-O(n) ; space- O(n)
# iterative DFS (all in 1) using 1 stack✅ time-O(n) ; space- O(n)
-----------------------------------------------------------------------------------
1. Recursive DFS
---------------------------------------------------------------------------------------------------------------
2. BFS-
- current level wale saare elements queue mein se pop karke temp mein store krlo
- saath mein har element k children ko queue mein push krte rho
- temp mein jo ek level waale saare elements hai vo ans mein push krdo
- ab next level walo k liye repeat krte rho...
3. iterative DFS (using stacks)-
2. push its right child and then left child into stack (opposite of expected since LIFO)
3. repeat
---------------------------------------------
b) In Order (using 1 stack) 🔥🔥
go deepest in left pushing all nodes into stack
when you get null then pop & print st.top
now go to right of this last node and again repeat.
1. till element != NULL , push kro AUR left mein jaao
2. when element ==NULL, print st.top and pop it and move to its right & repeat step 1
c) Post Order ⭐
- METHOD-1: using 2 stack
- METHOD-2: using 1 stack (rare)
- Method-3 : Using 1 stack & 1 vector
we will store elements in a stack as (node, num)
pushing root node initially s.t. it's pairwise num will be 1
3: post (no ++ is reqd & pop this pair from stack now)















Comments
Post a Comment