力扣刷题-94 中序遍历

'''
	第94题
'''

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
	# 递归
    def inorderTraversal(self, root: TreeNode) -> List[int]:
        if not root:
            return []
        tree = []
        def inorder(root):
            if not root:
                return
            if root.left:
                inorder(root.left)
            tree.append(root.val)
            if root.right:
                inorder(root.right)
        inorder(root)
        return tree

遍历二叉树的非递归方法,借助栈

# 前序遍历-解法1
class Solution:
    def preorderTraversal(self, root: TreeNode) -> List[int]:
        if root == None:
            return []
        ret = [root]
        tree = []
        while ret:
            node = ret.pop()
            tree.append(node.val)
            if node.right:
                ret.append(node.right)
            if node.left:
                ret.append(node.left)
        return tree

# 前序遍历-解法2
class Solution:
    def preorderTraversal(self, root: TreeNode) -> List[int]:
        if root == None:
            return []
        cur = root
        res = []        # 记录结果
        stack = []      # 辅助栈
        while cur or stack:
            while cur:
                stack.append(cur)
                res.append(cur.val)
                cur = cur.left
            cur = stack.pop()
            cur = cur.right
        return res

# 中序遍历
class Solution:
    def inorderTraversal(self, root: TreeNode) -> List[int]:
        if root == None:
            return []
        res = []
        stack = []
        cur = root
        while cur or stack:
            while cur:
                stack.append(cur)
                cur = cur.left
            cur = stack.pop()
            res.append(cur.val)
            cur = cur.right
        return res
# 后序遍历,使用前序遍历的方法,最后翻转,即根->右->左翻转为左->右->根
class Solution:
    def postorderTraversal(self, root: TreeNode) -> List[int]:
        if not root:
            return []
        res = []
        stack = []
        cur = root
        while cur or stack:
            while cur:
                res.append(cur.val)
                stack.append(cur)
                cur = cur.right
            cur = stack.pop()
            cur = cur.left
        return res[::-1]

你可能感兴趣的:(leetcode)