바위타는 두루미

[leetcode]116. Populating Next Right Pointers in Each Node 본문

Study/Algorithm

[leetcode]116. Populating Next Right Pointers in Each Node

DoRoMii 2019. 8. 9. 12:31
728x90

116. Populating Next Right Pointers in Each Node

 

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.

 

"""
# Definition for a Node.
class Node(object):
    def __init__(self, val, left, right, next):
        self.val = val
        self.left = left
        self.right = right
        self.next = next
"""
class Solution(object):
    def connect(self, root):
        parents =[]
        currents = []
        if root : 
            currents.append(root)
        
        while currents:
            parents = currents
            currents = []
            for p in parents:
                if p.left :
                    currents.append(p.left)
                if p.right:
                    currents.append(p.right)
            len_p = len(parents)
            for i in range(len_p):
                if i < len_p-1 :
                    parents[i].next = parents[i+1]
                else :
                    parents[i].next = None
        return root

같은 알고리즘 더  간단한 코드 

"""
# Definition for a Node.
class Node(object):
    def __init__(self, val, left, right, next):
        self.val = val
        self.left = left
        self.right = right
        self.next = next
"""
class Solution(object):
    def connect(self, root):
        nodes = [root] if root else []
        
        while nodes:
            next_nodes = []
            last = None
            for node in nodes:
                if last :
                    last.next = node
                if node.left :
                    next_nodes.append(node.left)
                if node.right:
                    next_nodes.append(node.right)
                last = node
            nodes = next_nodes
        return root

 

 

https://leetcode.com/problems/populating-next-right-pointers-in-each-node/

Comments