二叉树的前序、中序、后续遍历-python

二叉树的介绍:二叉树-leetcode

前序:

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

class Solution(object):
    def preorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        if root is None:
            return []
        stack = [root]
        res = []
        while stack :
            temp = stack.pop()
            res.append(temp.val)
            if temp.right:
                stack.append(temp.right)
            if temp.left:
                stack.append(temp.left)
        return res

中序:

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

class Solution(object):
    def inorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        if root is None:
            return []
        res=[]
        stack = []
        temp = root
        while stack or temp:
            while temp:
                stack.append(temp)
                temp=temp.left
            temp = stack.pop()
            res.append(temp.val)
            temp=temp.right
        
        return res

后序:

dbq  写完了来补上……

你可能感兴趣的:(二叉树的前序、中序、后续遍历-python)