给出一棵二叉树,返回其中序遍历
样例 1:
输入:{1,2,3} 输出:[2,1,3] 解释: 1 / \ 2 3 它将被序列化为{1,2,3} 中序遍历
样例 2:
输入:{1,#,2,3} 输出:[1,3,2] 解释: 1 \ 2 / 3 它将被序列化为{1,#,2,3} 中序遍历
你能使用非递归算法来实现么?
非递归写法
""" 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 inorderTraversal(self, root): # write your code here #先一路向左,压栈,然后依次访问,存在左节点,则继续向左 stack = [] output = [] while stack or root: #先压栈 while root: stack.append(root) root = root.left #然后依次访问,pop掉最后一个left节点 root = stack.pop() output.append(root.val) root = root.right return output