1. 程式人生 > >leetcode 每個結點的右指標 python

leetcode 每個結點的右指標 python

1 # Definition for binary tree with next pointer. 2 # class TreeLinkNode: 3 # def __init__(self, x): 4 # self.val = x 5 # self.left = None 6 # self.right = None 7 # self.next = None 8 9 class Solution: 10 # @param root, a tree link node 11 # @return nothing
12 def connect(self, root): 13 if root is None: 14 return root 15 tree = [[root]] 16 i = 0 17 while i < len(tree): 18 cur = tree[i] 19 layer = [] 20 for c in cur: 21 if c.left is not None: 22 layer.append(c.left)
23 if c.right is not None: 24 layer.append(c.right) 25 26 if layer: 27 tree.append(layer) 28 29 i += 1 30 for l in tree: 31 for i in range(len(l)-1): 32 l[i].next = l[i+1]
33