Populating Next Right Pointers in Each Node - Leetcode 116 - Python

แชร์
ฝัง
  • เผยแพร่เมื่อ 27 ม.ค. 2025

ความคิดเห็น • 82

  • @andreytamelo1183
    @andreytamelo1183 2 ปีที่แล้ว +3

    Thanks!

  • @DavidDLee
    @DavidDLee ปีที่แล้ว +14

    My approach was to do a standard layer by layer BFS and just ensure the order of the layer is left to right.
    I think it is better only because it looks exactly like a standard BFS, without confusing expressions like cur.left.next = cur.right

    • @tanishq2766
      @tanishq2766 ปีที่แล้ว +5

      Yeah but the follow up says to do it in O(1) excluding the recursion stack space

    • @mgnfy-view
      @mgnfy-view ปีที่แล้ว +3

      Yeah, I did it the BFS way as well. Couldn't really think of a O(1) space solution.

    • @floatingfortress721
      @floatingfortress721 ปีที่แล้ว

      Actually it isn't confusing at all. We are just connecting left child and right child

  • @omerule0
    @omerule0 2 ปีที่แล้ว +6

    Hello, fantastic approach. I solved this problem with maths. The n'th layer has 2 to the power of n-1 nodes. I used breadth firist search and while I was pushing and popping from the queue, I was also counting the steps I took. If the steps were lower than pow(2, power), link it to the next element in queue; if its equal, link it to nullptr and increase power by one and set the counter to zero. Hope this helps somebody.

  • @ladydimitrescu1155
    @ladydimitrescu1155 ปีที่แล้ว +4

    Can you make a video on populating Next Right Pointers in Each Node II - Leetcode 117?

  • @shourya436
    @shourya436 2 ปีที่แล้ว +19

    Ohhhhh man!!!!
    I had my Google interview today and guess what I proposed the same bfs solution and later he asked for O(1) space solution.
    Only if you could have uploaded this video earlier, i would have made it. 😭 😭

    • @memeproductions4182
      @memeproductions4182 2 ปีที่แล้ว +1

      Wait they rejected you because of this?:(

    • @shourya436
      @shourya436 2 ปีที่แล้ว +3

      @@memeproductions4182 yup man :(
      They told like you need to work on optimization

    • @memeproductions4182
      @memeproductions4182 2 ปีที่แล้ว

      @@shourya436 i'm sorry dude

    • @halahmilksheikh
      @halahmilksheikh 2 ปีที่แล้ว +19

      This is why programming interviews are a complete joke. You know the trick or you don't.

    • @hillarioushollywood4267
      @hillarioushollywood4267 2 ปีที่แล้ว

      @@halahmilksheikh absolutely.

  • @SkyeTian
    @SkyeTian 2 ปีที่แล้ว +2

    More concise? --
    class Solution:
    def connect(self, root):
    cur, nxt = root, root.left if root else None
    while cur and nxt:
    cur.left.next = cur.right
    if cur.next:
    cur.right.next = cur.next.left
    cur = cur.next
    else:
    cur = nxt
    nxt = cur.left
    return root

  • @wrishavbhattacharyya5216
    @wrishavbhattacharyya5216 2 ปีที่แล้ว +9

    This is by far the most intuitive solution thanks Neetcode

  • @Vivek_Hatte
    @Vivek_Hatte 2 หลายเดือนก่อน

    Great video, loved the solution. Very easy to visualize!

  • @poptart007-b2r
    @poptart007-b2r 2 ปีที่แล้ว +5

    Nice solution, i tried to refactor your optimal solution and add comments so it could make sens to me
    class Solution:
    def connect(self, root: 'Optional[Node]') -> 'Optional[Node]':
    n_0, n_1 = root, root.left if root else None
    # n_0 is our pointer to the current layer
    # n_1 is our pointer to next layer
    # We use n_0 to connect all the nodes belonging to next layer, meaning the layer n_1 belongs to.
    while n_1: # while there is a next layer to connect, we continue
    n_0.left.next = n_0.right # 1st action we can always do if there is a next layer after n_0
    if n_0.next: # 2nd action we might be able to do if we are not all the way to the right
    n_0.right.next = n_0.next.left
    n_0 = n_0.next
    continue # we keep going to the "right" until the layer is all connected
    n_0, n_1 = n_1, n_1.left # "Recursive call" to handle the next layer
    # The "Recursive call" can only happen because we used n_0 to connect the layer n_1 belongs to,
    # And we will use n_1 to connect the layer n_2 belongs to and so on.
    # There are only two types on connections to build at most, and we can do it from n_0 everytime
    return root

  • @sarthakchafle
    @sarthakchafle 11 หลายเดือนก่อน

    In the currently given example in leetcode, when the cur points to node with val=3, curr.left.next=curr.right this becomes null.

  • @kishores5121
    @kishores5121 2 ปีที่แล้ว +3

    How is it related to binary search? In neetcode practice list, it is under the binary search section. @NeetCode

    • @kyraluu
      @kyraluu ปีที่แล้ว +1

      yeah i have the same question here

  • @smart7868
    @smart7868 ปีที่แล้ว +1

    Simple pre-order recursion
    class Solution:
    def connect(self, root: 'Optional[Node]') -> 'Optional[Node]':
    if root and root.left:
    root.left.next = root.right
    if root.next:
    root.right.next = root.next.left
    self.connect(root.left)
    self.connect(root.right)
    return root

    • @rickk3300
      @rickk3300 ปีที่แล้ว

      O(N) recursion stack space 🙂

    • @tanishq2766
      @tanishq2766 ปีที่แล้ว

      Not an issue apparently, check leetcode’s follow-up

  • @horcruxone
    @horcruxone 10 หลายเดือนก่อน +10

    the problem has been changed now and they no longer give a "perfect binary tree". As such you will get errors with the above code.

  • @vdyb745
    @vdyb745 2 ปีที่แล้ว +5

    Wow !!!! I am awed at how you have solved this problem !!! 🙇‍♂

  • @vikaskumarojha8616
    @vikaskumarojha8616 6 หลายเดือนก่อน

    Most intuitive solution.

  • @BZ2EZSWE
    @BZ2EZSWE 2 ปีที่แล้ว

    You can make it run slightly faster by keeping the while loop as while nxt: because we want to stop when the nxt node pointer is null meaning current is the leftmost leaf node and next is null.

  • @giteshkhanna2633
    @giteshkhanna2633 หลายเดือนก่อน

    Very well explained!

  • @aadil4236
    @aadil4236 ปีที่แล้ว +3

    I did it with the queue data structure initially. It did pass but the code was too much. But you did it so efficiently! Neat code indeed! Thanks!

  • @vantrongvo6468
    @vantrongvo6468 2 ปีที่แล้ว

    very clear explantation, thank you!

  • @ankitgoyal8556
    @ankitgoyal8556 11 หลายเดือนก่อน +1

    Amazing dude, seems like I am ready for Google ;)

  • @seohyeongjeong
    @seohyeongjeong 2 ปีที่แล้ว

    Thanks for going through the problem step by step. I was wondering the difference between writing cur.left.next = cur.right in line 16 instead of nxt.next = cur.right.

    • @SkyeTian
      @SkyeTian 2 ปีที่แล้ว

      We can't do nxt.left 'cause nxt is always the first cur left node while cur goes on to the next one (i.e., to its right)

  • @mr.unknown4124
    @mr.unknown4124 3 หลายเดือนก่อน +1

    I am a beginner and despite efforts i am not getting good at it. my approach is i try to solve it myself, watch the video understand it and solve it but after sometimes if i approach the problem again it's nearly imposible for me to come up with a solution. Is this normal or am I doing something wrong.

    • @baghi_w
      @baghi_w 2 หลายเดือนก่อน

      it gets easier but you have to do it everyday

  • @akshayagarwal9311
    @akshayagarwal9311 ปีที่แล้ว

    Best video yet

  • @sabrinahossain8958
    @sabrinahossain8958 ปีที่แล้ว

    05:20 Optimized Solution

  • @ankurbhambri9199
    @ankurbhambri9199 2 ปีที่แล้ว +2

    "447. Number of Boomerangs" please solve this problem next at leetcode

  • @040princekumarverma4
    @040princekumarverma4 10 หลายเดือนก่อน

    I dont understand the code.
    Since there are several testcases which are not going to be solved by this code.(in my view) .
    For example consider testcase: [ 1, null, 2, 3, 4 ].
    Since the loop will works only if the root and root.left both are not None .But in the above test case we can clearly see that the (root != None but root.left != None) loop wil not work at all and tree's root is returned without any change to it.
    If i am wrong please to correct me.(That will help alot)
    Thanks.

  • @icedmosha6375
    @icedmosha6375 2 ปีที่แล้ว +1

    Damn, really an awesome solution

  • @ismaelmehdid
    @ismaelmehdid 3 หลายเดือนก่อน +1

    thanks!

  • @jiahongdai9782
    @jiahongdai9782 2 ปีที่แล้ว +1

    How to solve the followed up, 117?

  • @jhinthefourth8838
    @jhinthefourth8838 6 หลายเดือนก่อน

    Explanation is awesome but your solution only works if the input is a perfect tree, which is not the case of this LC quesiton.

  • @vaalarivan_p
    @vaalarivan_p 2 ปีที่แล้ว +1

    4:35 - 6:10

  • @rafishaik2496
    @rafishaik2496 2 ปีที่แล้ว

    hey are u providing any dsa courses or else are u teaching all this codes at any specific channel

  • @yueyue04011
    @yueyue04011 ปีที่แล้ว

    So clear!

  • @selfishmango
    @selfishmango 2 ปีที่แล้ว +1

    Do you use python while working in Google ??

  • @bkdhanush9017
    @bkdhanush9017 2 หลายเดือนก่อน

    @NeetCode i am watching and coding this problem right now. It is saying its wrong. The answer got out dated. Please check and modify it
    class Solution:
    def connect(self, root: 'Node') -> 'Node':
    if not root:
    return None
    queue = deque([root])

    while queue:
    size = len(queue)
    prev = None
    for _ in range(size):
    node = queue.popleft()
    if prev:
    prev.next = node
    prev = node

    if node.left:
    queue.append(node.left)
    if node.right:
    queue.append(node.right)

    prev.next = None

    return root
    This answer works!!

  • @bashaarshah2974
    @bashaarshah2974 2 ปีที่แล้ว

    You're a beast man!

  • @PlamenTheArmwrestler
    @PlamenTheArmwrestler 2 ปีที่แล้ว +1

    Can you add the java solution in the description of your video please.

    • @suraj8092
      @suraj8092 11 หลายเดือนก่อน

      It's there in his site

  • @floatingfortress721
    @floatingfortress721 ปีที่แล้ว

    Wow in ten minutes you covered three approaches: BFS with queue, DFS recursive, and two pointer leveraging techniques from the other two approaches. Awesome job!

  • @gilly4115
    @gilly4115 2 ปีที่แล้ว

    I get an error from line 16. If cur.next.left does not exist on line 18, the cur.left.next is an None type. Am I missing something?

    • @rishabhkhurana7203
      @rishabhkhurana7203 2 ปีที่แล้ว

      you are given aperfect binary tree means curr.next.left must exist

    • @tsunghan_yu
      @tsunghan_yu 2 ปีที่แล้ว +2

      You're probably doing LC 117 instead of 116.

    • @vvek_7
      @vvek_7 ปีที่แล้ว

      @@tsunghan_yu thank you, I had the same problem

  • @butoyighyslain171
    @butoyighyslain171 7 หลายเดือนก่อน

    mannnnn this is great!

  • @Immaybenotforthenextsecond
    @Immaybenotforthenextsecond ปีที่แล้ว

    117. Populating Next Right Pointers in Each Node II
    Need

  • @ihsannuruliman3656
    @ihsannuruliman3656 2 ปีที่แล้ว

    Hi, could you make a video on 542. 01 Matrix? I'm terrible at graph and all the videos on YT about it kinda asumming people already know about graph.

  • @poptart007-b2r
    @poptart007-b2r 2 ปีที่แล้ว

    The equivalent solution with "actual" recursion of the most optimal solution you presented(i think it is?? Anyone can correct me if you think i am wrong)
    class Solution:
    def connect(self, root: 'Optional[Node]') -> 'Optional[Node]':
    def dfs(node, nxtLayerNode):
    if nxtLayerNode:
    node.left.next = node.right
    while node and node.next:
    node.right.next = node.next.left
    node = node.next
    node.left.next = node.right
    dfs(nxtLayerNode, nxtLayerNode.left)
    dfs(root, root.left if root else None)
    return root

    • @lordsixth5944
      @lordsixth5944 2 ปีที่แล้ว

      By optimal he's saying it does not using extra memory while ur solutions using o(n) memory in system stack because of recursion

    • @poptart007-b2r
      @poptart007-b2r 2 ปีที่แล้ว

      @@lordsixth5944 Yep, i was just trying to make the recursive equivalent for what its worth

  • @midasredblade236
    @midasredblade236 2 ปีที่แล้ว +1

    FYI, *node* has been replaced with *root*

  • @SlateCode
    @SlateCode ปีที่แล้ว

    Can you make on this also... plz.. 117. Populating Next Right Pointers in Each Node II

    • @gopeshkhandelwal9823
      @gopeshkhandelwal9823 ปีที่แล้ว

      I solved it using the above approach. Following is my code-
      leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/solutions/4376497/o-n-time-complexity-o-1-space-complexity-without-recursion-solution/

  • @CST1992
    @CST1992 9 หลายเดือนก่อน

    That O(1) solution is brilliant. I coded up the "regular" BFS solution in 2 minutes, but this - this is so much better.

  • @CarlosRodriguezEscamilla
    @CarlosRodriguezEscamilla 14 วันที่ผ่านมา

    bro...what? lol. I just did a regular BFS. Awesome solution btw.

  • @FUNTasticFlutter
    @FUNTasticFlutter 9 หลายเดือนก่อน

    this exact same code not working for mw failing fiest test case
    class Solution:
    def connect(self, root: 'Node') -> 'Node':
    cur,nxt = root, root.left if root else None
    while cur and nxt:
    if cur.left:
    cur.left.next = cur.right
    if cur.next:
    cur.right.next= cur.next.left

    cur = cur.next
    if not cur:
    cur = nxt
    nxt= cur.left
    return root

    • @basileatsougan
      @basileatsougan 9 หลายเดือนก่อน +1

      The problem has changed now.In the video, it was about a PERFECT BINARY TREE, now in the leetcode problem, the binary tree is not a perfect binary tree

  • @vgsuresh
    @vgsuresh 2 ปีที่แล้ว

    was anyone able to solve `117. Populating Next Right Pointers in Each Node II` with this same approach ? I am kind of stuck with few test cases

    • @gopeshkhandelwal9823
      @gopeshkhandelwal9823 ปีที่แล้ว

      I solved it using the same approach. Following is my code-
      leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/solutions/4376497/o-n-time-complexity-o-1-space-complexity-without-recursion-solution/

  • @Dhanushh
    @Dhanushh ปีที่แล้ว

    chef kiss

  • @Sheverdin
    @Sheverdin 2 ปีที่แล้ว +1

    It doesn't work any more.

  • @metarus208
    @metarus208 2 ปีที่แล้ว

    Quite a deceptive problem.

  • @starstarhaha
    @starstarhaha ปีที่แล้ว

    cur in while is not neccesary, I have verified it.

  • @scienceshorts1234
    @scienceshorts1234 2 หลายเดือนก่อน

    man, is it just me, or anyone else getting runtime error?

  • @FreeStuff4TheWorld
    @FreeStuff4TheWorld 2 ปีที่แล้ว

    notification squad

  • @ax5344
    @ax5344 10 หลายเดือนก่อน

    I cannot find the python code in OP's website, but with the code I copied from the video, it is showing Null errors in 2024 March. Here is the (not working) code:
    class Solution:
    def connect(self, root: 'Node') -> 'Node':
    cur, nxt = root, root.left if root else None
    while cur and nxt:
    cur.left.next = cur.right
    if cur.next:
    cur.right.next = cur.next.left
    cur = cur.next
    if not cur:
    cur = nxt
    nxt = cur.left
    return root

    • @horcruxone
      @horcruxone 10 หลายเดือนก่อน

      the problem has been changed now and they no longer give a "perfect binary tree". As such you will get errors with the above code.

    • @ax5344
      @ax5344 10 หลายเดือนก่อน

      @@horcruxoneI see. Thanks!

  • @scienceshorts1234
    @scienceshorts1234 2 หลายเดือนก่อน

    c++ code anyone?