当前位置:网站首页>Xiaohei leetcode surfing: 94. Inorder traversal of binary tree

Xiaohei leetcode surfing: 94. Inorder traversal of binary tree

2022-08-04 23:19:00 little black invincible

小黑答案:递归

# 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]:
        arr = []
        if not root:
            return arr
        
        def mid_root(node):
            if node:
                mid_root(node.left)
                arr.append(node.val)
                mid_root(node.right)
        mid_root(root)
        return arr

在这里插入图片描述

小黑答案:非递归

# 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]:
        arr = []
        if not root:
            return arr
        q = []
        node = root
        # Push all the children of the root node onto the stack
        while node:
            q.append(node)
            node = node.left
        
        while q:
            # 结点出栈
            node = q.pop()
            # 打印
            arr.append(node.val)
            # Begin to facilitate the right child
            temp = node.right
            while temp:
                q.append(temp)
                temp = temp.left
        return arr

在这里插入图片描述

迭代法

# 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]:
        arr = []
        if not root:
            return arr
        q = []
        node = root
        while node or q:
            while node:
                q.append(node)
                node = node.left
            node = q.pop()
            arr.append(node.val)
            # turn right
            node = node.right
        return arr

在这里插入图片描述

方法三:Morris 中序遍历 未来实现

原网站

版权声明
本文为[little black invincible]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/216/202208042313413172.html