给定一个二叉树,返回它的中序 遍历。
Example:
Input: [. 1, null, 2,3] . 1 \ 2 / . 3 Output: [1,3,2]
Advanced: The recursive algorithm is very simple, can you do it through an iterative algorithm?
Binary tree traversal
Don't want to use recursion, try looping.
Code
def inorderTraversal(self, root: TreeNode) -> List[int]:
ans = []
if root is not None:
stack, temp = [], root
while stack or temp is not None:
if temp is not None:
stack.append(temp)
temp = temp.left
else:
temp = stack.pop()
ans.append(temp.val)
temp = temp.right
return ans