leetcode/94.二叉树的中序遍历.py
Ching b447d032a7 feat(leetcode; utils): 94.二叉树的中序遍历
94.二叉树的中序遍历

Signed-off-by: Ching <loooching@gmail.com>
2022-01-23 16:22:06 +08:00

58 lines
1.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#
# @lc app=leetcode.cn id=94 lang=python3
#
# [94] 二叉树的中序遍历
#
# 中序遍历LDR是二叉树遍历的一种也叫做中根遍历、中序周游。在二叉树中
# 中序遍历首先遍历左子树,然后访问根结点,最后遍历右子树。
# @lc code=start
# 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
from typing import Optional, List
from utils import *
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
res = []
stack = []
if root:
stack.append(root)
while stack:
node = stack[-1]
if node:
# 将该节点弹出,避免重复操作,下面再将右中左节点添加到栈中
stack.pop()
# 添加右节点(空节点不入栈)
if node.right:
stack.append(node.right)
# 添加中节点
stack.append(node)
# 中节点访问过,但是还没有处理,加入空节点作为标记
stack.append(None)
# 添加左节点(空节点不入栈)
if node.left:
stack.append(node.left)
else: # 只有在遇到空节点的时候,才将下一个节点放进结果集中
# 将空节点弹出
stack.pop()
# 重新取出栈中元素
node = stack.pop()
res.append(node.val)
return res
s = Solution()
root = creatBTree([1, None, 2], 0)
s.inorderTraversal(root)
# @lc code=end