94.二叉树的中序遍历 python3

题目:

94.二叉树的中序遍历 python3_第1张图片

思路:

  • 深度优先

代码:

# 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%的人,出乎意料。

你可能感兴趣的:(leetcode,题目)