Populating Next Right Pointers in Each Node II @ LeetCode (Python)
kitt
posted @ 2014年3月21日 23:26
in LeetCode
, 3779 阅读
从这里看到一种很巧妙的解法, 在遍历当前层时, 构建下一层。
I saw a wonderful solution here. When traversing the current level, build the next level.
# class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # self.next = None class Solution: # @param root, a tree node # @return nothing def connect(self, root): curr = root while curr: firstNodeInNextLevel = None prev = None while curr: if not firstNodeInNextLevel: firstNodeInNextLevel = curr.left if curr.left else curr.right if curr.left: if prev: prev.next = curr.left prev = curr.left if curr.right: if prev: prev.next = curr.right prev = curr.right curr = curr.next curr = firstNodeInNextLevel # turn to next level