[LeetCode] 589. N-ary Tree Preorder Traversal_Easy

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都可以.

 04/17/2019 update: 加第三种方法, 利用divide and conquer

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:
                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]:
                stack.append(each)
        return ans

 

3. Divide and conquer

# Divide and conquer
class Solution:
    def preOrder(self, root):
        if not root: return []
        temp = []
        for each in root.children:
            temp += self.preOrder(each)
        return [root.val] + temp

 

转载于:https://www.cnblogs.com/Johnsonxiong/p/9348912.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值