迭代:二叉树三序遍历一气呵成
实现二叉树先序,中序和后序遍历
http://www.nowcoder.com/questionTerminal/a9fec6c46a684ad5a3abd4e365a9d362
巧用栈中数据类型判断,以此迭代,一气呵成
# class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # # # @param root TreeNode类 the root of binary tree # @return int整型二维数组 # class Solution: def threeOrders(self , root ): stack1, stack2, stack3 = [root], [root], [root] res1, res2, res3 = [], [], [] while stack1: i, j, k = stack1.pop(), stack2.pop(), stack3.pop() if isinstance(i, TreeNode): stack1.extend([i.right, i.left, i.val]) if isinstance(j, TreeNode): stack2.extend([j.right, j.val, j.left]) if isinstance(k, TreeNode): stack3.extend([k.val, k.right, k.left]) if isinstance(i, int): res1.append(i) if isinstance(j, int): res2.append(j) if isinstance(k, int): res3.append(k) return [res1, res2, res3]