按之字形顺序打印二叉树 牛客网 剑指Offer
题目描述请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。 # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def Print(self,root): if not root: return [] levels,result,leftToRight = [root],[],True while levels: curValues,nextLevel = [],[] for node in levels: curValues.append(node.val) if node.left: nextLevel.append(node.left) if node.right: nextLevel.append(node.right) if not leftToRight: curValues.reverse() if curValues: result.append(curValues) levels = nextLevel leftToRight = not leftToRight return result
转载于:https://www.cnblogs.com/vercont/p/10210381.html