jinhuang1102

116. Populating Next Right Pointers in Each Node

Nov 17th, 2018
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.71 KB | None | 0 0
  1. 这题不要想多了,如果在一层中间有 Null 的节点,那么此节点的 next 将指向下一个不是 Null 的节点。
  2. 方法一,用的是我最熟悉的 Level-Order-Traversal 的方法。
  3. class Solution:
  4.     # @param root, a tree link node
  5.     # @return nothing
  6.     def connect(self, root):
  7.         if not root:
  8.             return
  9.         q = collections.deque()
  10.         q.append(root)
  11.         q.append(None)
  12.         while q:
  13.             node = q.popleft()
  14.             if node is None:
  15.                 if not q:
  16.                     break
  17.                 q.append(None)
  18.             else:
  19.                 node.next = q[0]
  20.                 if node.left:
  21.                     q.append(node.left)
  22.                 if node.right:
  23.                     q.append(node.right)
  24.  
  25. #方法二,其实这道提示划归到了 DFS 的 topic 所以,这第二种方法,就是 DFS.
  26. #在这个方法中,需要两个指针,pre指针每一个loop都指向每个level的最左边的值。然后用cur指针来把最左边的node的左右子树用next串起来cur.left.next = cur.right。
  27. #如果,当前level还有右兄弟树,那么把当前node的右子树与右侧兄弟树的左子树串起来(cur.right.next = cur.next.left), 然后,cur = cur.next
  28. class Solution:
  29.     # @param root, a tree link node
  30.     # @return nothing
  31.     def connect(self, root):
  32.         if not root:
  33.             return
  34.         pre = root
  35.         cur = None
  36.         while pre.left:
  37.             cur = pre
  38.             while cur:
  39.                 cur.left.next = cur.right   #
  40.                 if cur.next:
  41.                     cur.right.next = cur.next.left
  42.                 cur = cur.next
  43.            
  44.             pre = pre.left
Add Comment
Please, Sign In to add comment