c++二叉树的层序遍历_leetcode 103. 二叉树的锯齿形层序遍历
生活随笔
收集整理的這篇文章主要介紹了
c++二叉树的层序遍历_leetcode 103. 二叉树的锯齿形层序遍历
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
按層次遍歷,記錄下對應節點的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總結
以上是生活随笔為你收集整理的c++二叉树的层序遍历_leetcode 103. 二叉树的锯齿形层序遍历的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mongodb mysql 写_MySQ
- 下一篇: 深入解析windows XP/2003: