【算法】二叉树遍历算法的python实现

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

前序遍历

https://leetcode.com/problems/binary-tree-preorder-traversal/description/

 #递归方法
class Solution:
    def __init__(self):
        self.res=[]
    def preorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        if root:
            self.res.append(root.val)
            self.preorderTraversal(root.left)
            self.preorderTraversal(root.right)
        return self.res
#非递归
class Solution:
    def preorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        res,stack=[],[root]
        while stack:
            node=stack.pop()
            if node:
                res.append(node.val)
                stack.append(node.right)
                stack.append(node.left)
        return res

中序遍历

https://leetcode.com/problems/binary-tree-inorder-traversal/description/

#递归方法
class Solution:
    def __init__(self):
        self.inorder=[]
    def inorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        if root:
            self.inorderTraversal(root.left)
            self.inorder.append(root.val)
            self.inorderTraversal(root.right)
        return self.inorder     
#非递归方法
class Solution:
    def inorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        res,stack=[],[]
        while True:
            while root:
                stack.append(root)
                root=root.left
            if not stack:
                return res
            node=stack.pop()
            res.append(node.val)
            root=node.right

层序遍历

https://leetcode.com/problems/binary-tree-level-order-traversal/description/

class Solution:
    def levelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        if not root:
            return []
        res,queue=[],[root]
        while queue:
            res.append([x.val for x in queue])
            # queue=[y for x in queue for y in [x.left,x.right] if y]
            for i in range(len(queue)):
                node=queue.pop(0)
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
        return res

后序遍历

https://leetcode.com/problems/binary-tree-postorder-traversal/description/

#递归方法
class Solution:
    def __init__(self):
        self.postorder=[]
    def postorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        if root:
            self.postorderTraversal(root.left)
            self.postorderTraversal(root.right)
            self.postorder.append(root.val)
        return self.postorder
#非递归方法一
class Solution:
    def postorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        if not root:
            return []
        res,stack=[],[root]
        while stack:
            node=stack.pop()
            res.append(node.val)
            if node.left:
                stack.append(node.left)
            if node.right:
                stack.append(node.right)
        return res[::-1]
#非递归方法二
class Solution:
    def postorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        res,stack=[],[(root,False)]
        while stack:
            node,flag=stack.pop()
            if node:
                if flag:
                    res.append(node)
                else:
                    stack.append((node,True))
                    stack.append((node.right,False))
                    stack.append((node.left,False))
        return res
    原文作者:PancakeCard
    原文地址: https://www.jianshu.com/p/81460d22e7bb
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞