每日leetcode-数组-94. 二叉树的中序遍历

分类:二叉树-二叉树的遍历

题目描述:

给定一个二叉树的根节点 root ,返回它的 中序 遍历。

解题思路:

递归:

# 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]:

        def inorder(root:TreeNode):
            if not root:
                return res
            inorder(root.left)
            res.append(root.val)
            inorder(root.right)
        res = []
        inorder(root)
        return res

迭代:

# 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 []
        res,stack = [],[]
        while stack or root: # stack为空且root为null时,说明已经遍历结束
            while root: # 可以深入左子树
                stack.append(root)
                root = root.left
            root = stack.pop() # 否则访问栈中节点,并深入右子树
            res.append(root.val)
            root = root.right
        return res
原文地址:https://www.cnblogs.com/LLLLgR/p/14978466.html