python 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: Optional[TreeNode]) -> List[int]:
        if not root:
            return []
        ls = []
        ls += self.inorderTraversal(root.left)
        ls.append(root.val)
        ls += self.inorderTraversal(root.right)
        return ls

迭代

# 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: Optional[TreeNode]) -> List[int]:
        if not root:
            return []
        ls = []
        stack = []
        current = root
        while current or stack:
            while current:
                stack.append(current)
                current = current.left
                # 此循环出去时current是None
            current = stack.pop() # 此时current是最左侧节点
            ls.append(current.val)
            current = current.right # 判断其右侧节点,如果有则,则重复上面的第二层while循环,否则会继续pop节点出来

        return ls

你可能感兴趣的:(LeetCode,python,leetcode)