欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

94.二叉树的中序遍历 python3

程序员文章站 2024-01-11 16:42:34
...

题目:

94.二叉树的中序遍历 python3

思路:

  • 深度优先

代码:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
from collections import deque

class Solution:
    def inorderTraversal(self, root: TreeNode) -> List[int]:
        result = []
        visited = set([])
        sta = deque([])
        if root:
            sta.append(root)
        
        while sta:
            front = sta.pop()
            if front not in visited:
                visited.add(front)
                if front.right:
                    sta.append(front.right)
                sta.append(front)
                if front.left:
                    sta.append(front.left)
            else:
                result.append(front.val)
        
        return result

总结:

  • 迭代实现的深度优先算法,打败93%的人,出乎意料。
相关标签: python3 leetcode