按层次遍历,记录下对应节点的val和所在层,然后经过一定变换得到输出。python代码如下:
# Definition for a binary tree node.# class TreeNode(object):# def __init__(self, x):# self.val = x# self.left = None# self.right = Noneclass Solution(object): def zigzagLevelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ tmp = [] if root == None: return tmp tmp.append(root) tmp_list = [] cengshu = 0 while(tmp != []): tmp_next = [] for i in range(len(tmp)): tmp_list.append([tmp[i].val , cengshu]) if tmp[i].left != None: tmp_next.append(tmp[i].left) if tmp[i].right != None: tmp_next.append(tmp[i].right) tmp = tmp_next cengshu += 1 from collections import defaultdict dict_new = defaultdict(list) for i in range(len(tmp_list)): dict_new[tmp_list[i][1]].append(tmp_list[i][0]) final_return = [] for i in range(len(dict_new.values())): if i % 2 == 0: final_return.append(dict_new.values()[i]) else: t = dict_new.values()[i] t.reverse() final_return.append(t) return final_return