非遞歸:
# 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: TreeNode) -> List[int]:
stack = []
ans = []
while root or stack:
while root:
stack.append(root)
root = root.left
if stack:
root = stack.pop()
ans.append(root.val)
root = root.right
return ans
遞歸:
# 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: TreeNode) -> List[int]:
self.ans = []
def func(root):
if not root: return None
func(root.left)
self.ans.append(root.val)
func(root.right)
func(root)
return self.ans