118. 二叉樹的鋸齒形層序遍歷
阿新 • • 發佈:2020-12-22
這是我的程式碼(它是不正確的,對的請看力扣,我這裡只是記錄一個有趣的函式)
import math class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None def __str__(self): return self.val root = TreeNode(3) t1 = TreeNode(9) t2 = TreeNode(20) t3 = TreeNode(None) t4 = TreeNode(None) t5 = TreeNode(15) t6 = TreeNode(7) t1.left = t3 t1.right = t4 t2.left = t5 t2.right = t6 root.left = t1 root.right = t2 class Solution(object): def zigzagLevelOrder(self, root): # 在寫這個的時候我以為root是滿二叉樹,也就是說沒有地方用None補齊 node_list = self.ground(root) # 這個函式是一個廣度遍歷二叉樹的函式 lenght = len(node_list) + 1 # 滿二叉樹的節點等於2^n -1 ,其中n是二叉樹的層數 cengji = int(math.log(lenght, 2)) # 這個是我用對數函式求出來的二叉樹層數 k = 0 # 其中k表示每次取擷取node_list的起始位置 ret_list = [] for i in range(1, cengji + 1): num = 2 ** (i-1) # 計算一層有幾個節點 cut_list = node_list[k: num + k] # num + k是擷取的最後位置 if i % 2: cut_list = cut_list else: cut_list = cut_list[::-1] cut_list = [item for item in cut_list if item] ret_list.append(cut_list) k += num return ret_list def ground(self, root): if not root: return retList = [] queue = [] queue.append(root) while queue: r = queue.pop(0) retList.append(r.val) if r.left: queue.append(r.left) if r.right: queue.append(r.right) return retList s1 = Solution() print(s1.zigzagLevelOrder(root))