力扣刷题-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]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值