Java soln using Recursion without any queue: public List levelOrder(TreeNode root) { List ans = new ArrayList(); travel(0, root, ans); return ans; } private void travel(int level, TreeNode cur, List ans) { if (cur == null) return; // add another list only when we visit a new level for the first time if (level >= ans.size()) ans.add(new ArrayList()); ans.get(level).add(cur.val); // get the list of that level add the node val to it travel(level + 1, cur.left, ans); travel(level + 1, cur.right, ans); }
@fantasyillusion2 жыл бұрын
For those looking for python code # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: ans=[] if root==None: return ans queue=deque([root]) while queue: n=len(queue) level=[] for i in range(n): node=queue.popleft() if node.left!=None: queue.append(node.left) if node.right!=None: queue.append(node.right) level.append(node.val) ans.append(level) return ans
@gunahawk68932 жыл бұрын
def levelOrder(self): if self.root == None: return else: self._levelOrder(self.root) def _levelOrder(self,curNode): q = [] q.append(curNode) while len(q) != 0: curNode = q.pop(0) print(curNode.value , end= " ") if curNode.left != None: q.append(curNode.left) if curNode.right != None: q.append(curNode.right)
@Rahul_Mongia7 ай бұрын
😅
@banothutharun27438 ай бұрын
what a fentastic explaination sir. simply superb
@krishnasudan34103 жыл бұрын
Just started it and loving it.. On point clear explanation.. No khich khich... No time waste.. Worth watching.. ♥️
@SB-hb2kx Жыл бұрын
The expaination was so good that even after 6months I was able to solve it without help. Thank you @Striver bhaiya
@PriyaGupta-sg4sm9 ай бұрын
No one has ever made level order this easy!
@susmitapatil48477 ай бұрын
He is the best tutor. Good job
@lifehustlers164 Жыл бұрын
9/54 (16% done)!!!
@kermitdaphrogge5252 ай бұрын
Are you now placed, brother?
@vganesh98298 ай бұрын
Understood Striver!😊
@cinime2 жыл бұрын
Understood! Super gorgeous explanation as always, thank you very much!!
@vedantsharma58763 жыл бұрын
Striver you are a boon to us Tier 3 Students :') Love you man!
@AdityaChaturvedi-20052 ай бұрын
Not only tier 3 students bro . He is a boon for everyone learning dsa
@RitikKumar-bk6pj2 жыл бұрын
Sir aap bahut bhadiya pdate ho thank u for making this series
@sukritikuila91612 жыл бұрын
Shouldn't be the Space Complexity : O(width) cause the queue can grow upto max nodes in a level ?
@manavshah74503 жыл бұрын
Understooooood!!! Awesome explanation. Please upload all videos by tomorrow, else after weekend u will get buzy with office :/
@PrashantSingh-jy6zp3 жыл бұрын
for best experience go to 0:41
@nawabkhan49162 жыл бұрын
great work, and have lots of sponsor ad so that you can provide great videos.
@averylazyandweirdhuman5 ай бұрын
I want to be hard working like you. You really live up to your channel name. ✌️
@shake-her39082 жыл бұрын
vector levelOrder(Node* node) { vector ans; queueq; q.push(node); while(!q.empty()){ //solving in hard way int size =q.size(); for(int i=0;ileft){ q.push(front->left); } if(front->right){ q.push(front->right); } ans.push_back(front->data); } } return ans; }
@yashshah660 Жыл бұрын
I have also written the same code but I got a wrong answer on GFG
@lourduradjou182 Жыл бұрын
superb bhai
@mayanksaurabhmayanksaurabh92712 жыл бұрын
very well explained. thanks a ton
@ganeshjaggineni40974 ай бұрын
NICE SUPER EXCELLENT MOTIVATED
@apmotivationakashparmar722Ай бұрын
Thank you so much striver.
@rajeshwari.s.r97036 ай бұрын
Thanks a lot …I understood very clearly✌🏻 dsa playlist helped a lot for me 😇😊🤩
@AkshayKumar-oi2cu2 жыл бұрын
No one can teach like u ...sir
@codeman38288 ай бұрын
Understood
@stith_pragya Жыл бұрын
Thank You So Much for this wonderful video.............🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻
@atharvakulkarni20243 жыл бұрын
Tablet Lectures are much much effective..Thanks a lot !!DP SERIES PLEASE
@nikitakeshri92335 ай бұрын
beautifully explained
@yashkhatwani31982 жыл бұрын
love you, bless you, thank you.
@FusionArcs2 жыл бұрын
You really are amazing at explaining things. Thanks, brother.
@deeptimayeemaharana24482 жыл бұрын
a for loop is there inside the while loop so how is the time complexity O(n)
@srirambharadwaj1937 Жыл бұрын
amazing explanation bhaiya
@bhavkushwaha7 ай бұрын
Thankyou Striver, Understood!
@utsavseth6573 Жыл бұрын
Superb Work RAJ.
@SatyamKumar-bw4vi2 жыл бұрын
Hare Krishna!
@md.imrankhan6912 Жыл бұрын
Great Striver
@ram_pande80393 жыл бұрын
you are doing a really great and self-less work. may you achieve all successes.
@samuelfrank1369 Жыл бұрын
UNDERSTOOD. THANKS A LOT
@deepikasrivastava30403 жыл бұрын
Thank you for the valuable and explanatory content.
@aadeshsharma00013 жыл бұрын
Bhaiya code is really very clean
@rohitmittal5142 жыл бұрын
Thanks bhai bhot help milti iss course se. Keep making such videos. Aur ek request h DBMS ka course bhi daal do.
@AtharvaRao01043 ай бұрын
A good teacher will tell why we need a queue to solve this.. here the teacher directly states to do a BFS we need a queue .. I'm sure a lot of people would not be able to explain from first principles ..
@hashcodez7577 ай бұрын
Understood Striver!!
@jasonbrody46183 жыл бұрын
Liked. Cfbr will watch after some time
@sarangkumarsingh79013 ай бұрын
Awesome................
@duckworth_lewis8 ай бұрын
Thx thx thx
@parul833411 ай бұрын
understood ❤❤ love u sir 🥰🥰
@cinime2 жыл бұрын
Understood! Super amazing explanation as always, thank you very much!!
@shubhamgite77302 жыл бұрын
thank u so much bhayya for this very important tree series & your explanation is at next level yarr bahot Simply samzaa dete hoo..🤗🤗
@sayantaniguha851911 ай бұрын
Why is the space complexity, O(n) & not the maximum number of nodes in any single level of the tree?
@sayantanmanna13604 ай бұрын
i.e. O(2*d), where 2 is the branching factor and d is the max level
@hetpatel17722 жыл бұрын
The Best Series on Tree
@nitantjoshi99033 жыл бұрын
In java why we did List wrapList = new LinkedList() instead of just using List list = new ArrayList(); And yes why q.offer() instead of using q.add() ?
@nipunsinha74453 жыл бұрын
q.add() will throw an exception if an insertion fails, so you will have to wrap it in a try-catch block...q.offer() returns a boolean to indicate if insertions was successful or not. More explaination here docs.oracle.com/javase/tutorial/collections/interfaces/queue.html - Check the Queue Interface structure table on this page.
@koushikvss76382 жыл бұрын
q.add() will throw an exception when there is no capacity to add more elements, whereas q.offer() will just return false.
@shashankkr10082 жыл бұрын
Clearly understood and coded, Thanks bhaiya!!!
@pritishpattnaik46742 жыл бұрын
Beautifully explained , amazing
@premsagargupta52632 жыл бұрын
Thank you brother, learning trees from your series, very helpful :)
@Ashutosh.3692 жыл бұрын
you wrote a lengthy code in java. we can use an arraylist to store the elements while traversing. here is the code how i have implemented void level_order( Node root ) { if( root == null ) return; ArrayList ans = new ArrayList(); // to store the elements Queue q = new ArrayDeque(); q.add( root ); while ( !q.isEmpty() ) { Node temp = q.poll(); if( temp.left !=null ) q.add( temp.left ); if( temp.right !=null ) q.add( temp.right ); ans.add( temp.data ); } System.out.println( ans ); } Narayan Narayan 😇😇
@Sungod.aditya2 ай бұрын
the function needed to return List
@owaisch34422 жыл бұрын
is it possible to find the level of a node using preorder traversal?
@eiji112825 ай бұрын
Sir why do we not using single vector and why do we use vector of vector???
@Tbm45458 күн бұрын
Is the levels needed ?? Or we can simply use a stack and print by sequnce.
@krentwhite26683 жыл бұрын
This video is used to solve Zigzag Level Order traversal also... Thanks Mr. Striver👏
@DeadPoolx1712Ай бұрын
UNDERSTOOD;
@shubamgoswami3 жыл бұрын
THAK GYA HU VROOO RELEVEL SUN SUN KE
@AyushGupta-kp9xf3 жыл бұрын
Complexity analysis at 7:36
@Mr.Indianwxvhehsy9191hghgx11 ай бұрын
nice video sir
@sayankarmakar132 жыл бұрын
Thanks bhaiya for great explanation
@ajaybachate71372 жыл бұрын
if queue has n nodes inside it and we traverse for n nodes to put into vector then wont it be O(N^2) time complexity?
@mriduljain1981 Жыл бұрын
completed lecture 8 of tree playlist.
@debugagrawal2 жыл бұрын
Bhaiya ap abhi 1 hi approach bata rahe ho, Recusrion se bhi mast hota hai, so as per interview point of view both approaches batao, better for all students, thanks in advance ♥
@LearnWithMe77775 ай бұрын
Understood❤
@Ramu911911 ай бұрын
Nice Video Brother Keep it up
@runtime3793 жыл бұрын
awsome lectures
@72nishantwadhawan5 Жыл бұрын
Best Content on the internet.
@rahulyadav8159 Жыл бұрын
variable levelNum is quite confusing in JAVA implementation.
@asthapandey9587 Жыл бұрын
Couldn't understand Java code
@wribo54333 жыл бұрын
You are amazing brother! Thank you for all the hard work you put for us
@shivanisinha70352 жыл бұрын
Such an amazing video
@divyanshuyadav55242 жыл бұрын
While declaring Queue...What is significance of * in ?? Why can"t be it only ??
@hakunamatata-nl4js6 ай бұрын
Thank you
@JohnWickea8 ай бұрын
Thanks a lot
@nagavedareddy58912 жыл бұрын
Huge respect..❤👏
@Versha_arya2 ай бұрын
Thank you ao muchh
@adebisisheriff15910 ай бұрын
Understood!!!
@NoxuzBlog2 жыл бұрын
thank you for the video
@yatharthahuja16352 жыл бұрын
amazing content😀
@Ammaradreamart Жыл бұрын
Best lecture
@s_sattu_sАй бұрын
is it a queue or stack? because the design looks similar to stack rather than queue
@shrishshrivastava4444 Жыл бұрын
Clarity 🔥🔥
@gandhijainamgunvantkumar67832 жыл бұрын
Amazing video bhaiya :)
@103himajapoluri6 Жыл бұрын
is bfs same as level order traversal
@willturner34403 жыл бұрын
why space complexity should not be O(width of tree) ?
@singhs_aniket3 жыл бұрын
Understood 👌👌
@Code_Solver3 жыл бұрын
Thank you Striver bayya
@DhruvSharma-mh5vf2 жыл бұрын
Well explained 👊
@elements86303 жыл бұрын
Best video I could find!!! Great job, keep up the good work bhaiya :-)
@ankitdubey93103 жыл бұрын
@take U forward striver bhaiya ye question tha ki : recursion and backtracking mein jab aap sochte ho koi sawal karne ke liye to aap kya ek cycle pura imagine karte ho? ya fir thoughtprocess kaise hota hai, mujhe approach samajh mein aa jati hai recursion and backtrack questions mein par likha nahi aata , please guide me
@gouravupadhyay90923 жыл бұрын
same question bro
@OtakuRiku3 жыл бұрын
Watch permutation and combination using backtracking... Most of the backtracking problem are based on that problem...
It's the approach of finding the maximum depth of the tree.
@ujjalbanerjee4372 Жыл бұрын
@@Pritamdaspk only the list line is different r8?
@AB-iv4bq Жыл бұрын
what is val??
@laveshchanchawat69832 жыл бұрын
int size = queue.size(); if we remove this line and directly use for(int i = 0; i < queue.size(); i++) why the output are different?
@petermj28042 жыл бұрын
because queue size will keep changing after popping each element,instead if we initialize the size before any of the elements are popped we don't have to worry about the queue size changing after each pop operation.