首页 > 其他 > 详细

[LeetCode] 589. N-ary Tree Preorder Traversal_Easy

时间:2018-07-22 10:23:04      阅读:207      评论:0      收藏:0      [点我收藏+]

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

 

For example, given a 3-ary tree:

技术分享图片

 

Return its preorder traversal as: [1,3,5,6,2,4].

 

这个题目思路就是跟LeetCode questions conlusion_InOrder, PreOrder, PostOrder traversal类似, recursive 和iterable都可以.

 

1. Recursively

class Solution:
    def nary_Preorder(self, root):
        def helper(root):
            if not root: return
            ans.append(root.val)
            for each in root.children:
                if each: 
                    helper(each)
        ans = []
        helper(root)
        return ans

 

2. Iterable

class Solution:
    def nary_preOrder(self, root):
        if not root: return []
        stack, ans = [root], []
        while stack:
            node = stack.pop()
            ans.append(node.val)
            for each in node.children[::-1]:
                if each:
                    stack.append(each)
        return ans

 

[LeetCode] 589. N-ary Tree Preorder Traversal_Easy

原文:https://www.cnblogs.com/Johnsonxiong/p/9348912.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!