post-custom-banner

๐Ÿ“„ Description

You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:
struct Node { int val; Node *left; Node *right; Node *next; }
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.

Initially, all next pointers are set to NULL.

Example 1:

Input: root = [1,2,3,4,5,6,7]
Output: [1,#,2,3,#,4,5,6,7,#]
Explanation: Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.

Example 2:

Input: root = []
Output: []

๐Ÿ’ป Solution (1) BFS

class Solution:
    def connect(self, root: 'Optional[Node]') -> 'Optional[Node]':
        if not root:
            return root
        
        queue=[]
        queue.append(root)
        
        while queue:
            temp=[]
            while queue:
                cur_node=queue.pop(0)
                if cur_node.left:
                    temp.append(cur_node.left)
                if cur_node.right:
                    temp.append(cur_node.right)
            for i in range(len(temp)-1):
                temp[i].next=temp[i+1]
            queue.extend(temp)
        
        return root
        
        print(queue)

๐Ÿ”Ž Complexity

๐Ÿ”จ My solution

There is simple rule for populating next right pointers in each node.

  • next right pointer for left child: parent's right node
  • next right pointer for right child: parent's next node's left node
    Because the default of Node.next=None, we don't have to worry about every last right child of every level.

๐Ÿ’ป Solution (2) Recursion

class Solution:
    def connect(self, root: 'Optional[Node]') -> 'Optional[Node]':
        if not root:
            return root
        
        def bfs(root):
            # if the node has child
            if root.left:
                # leftchild.next=parent.right
                root.left.next=root.right
                # rightchild.next=parent.next.left
                if root.next:
                    root.right.next=root.next.left
                # repeat the process with left&right child
                bfs(root.left)
                bfs(root.right)
        
        bfs(root)
        
        return root

๐Ÿ”Ž Complexity

๐ŸŽˆ Follow-up:

  • You may only use constant extra space.
  • The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.

References
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/1849143/Python-Easy-Solution-or-BFS-Traversal

profile
Make your lives Extraordinary!
post-custom-banner

0๊ฐœ์˜ ๋Œ“๊ธ€