【python3】从leetcode 114 & 589 讲解关于树的先序遍历题

先序遍历 preorder

遍历顺序:根结点-左子树-右子树,如下图蓝色为先序(4个算法的遍历结果都为12345)

1 递归写法

        def pretraversal(root):
            
            preval.append(root.val)
            if root.left:pretraversal(root.left)
            if root.right:pretraversal(root.right)

2 迭代写法

使用栈,后进先出,由于先序是根-左-右的顺序,append根之后要先pop出左子树的话,所以先append右child再append左child(倒转append)

        stack, preval = [root], []
        
        while stack:
            root = stack.pop()
            if root is not None:
                preval.append(root.val)
                if root.right is not None:
                    stack.append(root.right)
                if root.left is not None:
                    stack.append(root.left)
        
        return preval

3 morris traversal


树的结点定义

# Definition for a Node.
class Node(object):
    def __init__(self, val, children):
        self.val = val
        self.children = children

二叉树结点定义

# Definition for a binary tree node.
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

144. Binary Tree Preorder Traversal

Given a binary tree, return the preorder traversal of its nodes' values.

Example:

Input: [1,null,2,3]
   1
    \
     2
    /
   3

Output: [1,2,3]

Follow up: Recursive solution is trivial, could you do it iteratively?

class Solution(object):
    def preorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        if not root:return []
        preval = []
        def pretraversal(root):
            
            preval.append(root.val)
            if root.left:pretraversal(root.left)
            if root.right:pretraversal(root.right)
        pretraversal(root)
        return preval

 589. N-ary Tree Preorder Traversal

recursive

class Solution(object):
    def preorder(self, root):
        """
        :type root: Node
        :rtype: List[int]
        """
        preval = []
        if not root:return []
        def pretraversal(root):
            preval.append(root.val)
            for i in range(len(root.children)):
                pretraversal(root.children[i])
        pretraversal(root)
        return preval
        

iterative

class Solution(object):
    def preorder(self, root):
        """
        :type root: Node
        :rtype: List[int]
        """
        if not root:return []
        preval = []
        stack = []
        stack.append(root)
        while(stack):
            node = stack.pop()
            preval.append(node.val)
            for child in node.children[::-1]:
                stack.append(child)
        return preval

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值