Binary Tree Inorder Traversal
from typing import (
List,
)
from lintcode import (
TreeNode,
)
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: A Tree
@return: Inorder in ArrayList which contains node values.
"""
def inorder_traversal(self, root: TreeNode) -> List[int]:
# write your code here
res = []
stack = []
cur = root
#一个while判断cur和stack即可
while cur or stack:
while cur:
stack.append(cur)
cur = cur.left
cur = stack.pop()
#List函数没有add
res.append(cur.val)
#只移动指针,不需要塞入栈,因为中序的话root已经遍历了,右树可以直接遍历无需栈。
cur = cur.right
#记得返回结果
return res
Last updated