# class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # # # @param root TreeNode类 # @return int整型一维数组 # class Solution: def preorderTraversal(self , root ): # write code here reList = [] if root is None: return reList stack = [] node = root while node is not None: if isinstance(node.val, int): reList.append(node.val) if node.right is not None: stack.append(node.right) node = node.left if node is None and len(stack)>0: node = stack.pop(-1) return reList 前序遍历的迭代算法关键在于:设置一个栈,每次将节点的右孩子压入栈中,当遍历完根节点和左子树,便从栈中弹出右子树,继续循环深入
|