0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

LeetCodeを1日1題解いてみる (day43)

Last updated at Posted at 2024-12-16

43日目に取り組んだ問題はこちら!
今日からまた、アルゴリズムの問題に戻ります。

589. N-ary Tree Preorder Traversal

問題文

Given the root of an n-ary tree, return the preorder traversal of its nodes' values.

Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value

僕の回答

"""
# Definition for a Node.
class Node:
    def __init__(self, val: Optional[int] = None, children: Optional[List['Node']] = None):
        self.val = val
        self.children = children
"""

class Solution:
    def preorder(self, root: 'Node') -> List[int]:
        stack = [root]
        result = []
        
        while stack:
            node = stack.pop()
            if not node:
                if not stack:
                    break
                else:
                    continue
            
            result.append(node.val)
            for child in node.children[::-1]:
                stack.append(child)
        
        return result

より効率の良い回答例

"""
# Definition for a Node.
class Node:
    def __init__(self, val: Optional[int] = None, children: Optional[List['Node']] = None):
        self.val = val
        self.children = children
"""

class Solution:
    def preorder(self, root: 'Node') -> List[int]:
        if not root:  # rootがNoneの場合の早期リターン
            return []

        stack = [root]
        result = []
        
        while stack:
            node = stack.pop()
            if not node:
                continue
            
            result.append(node.val)
            if node.children:  # 子ノードがある場合のみ処理
                for child in node.children[::-1]:
                    stack.append(child)
        
        return result

学んだこと

  • 以下の部分はcontinueで次のwhileで確認されるので不必要だった。

    if not stack:
        break
    
  • 配列に後ろからアクセスする方法はarr[::-1]

コメント

今回の問題はすぐに思いついて、エラーなしで一回で成功したのでとても嬉しい!

次の問題はこちら!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?