Question: https://oj.leetcode.com/problems/populating-next-right-pointers-in-each-node/
Question Name: Populating Next Right Pointers in Each Node
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | # Definition for a binary tree node # 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): fatherLayerCurrent = root sonLayerHead = None sonLayerCurrent = None # Travel layer by layer as BFS travesal. while fatherLayerCurrent != None: # Travel inside a layer from left to right while fatherLayerCurrent != None: # Try to access the left son if there is if fatherLayerCurrent.left != None: if sonLayerHead == None: sonLayerHead = fatherLayerCurrent.left sonLayerCurrent = sonLayerHead else: sonLayerCurrent.next = fatherLayerCurrent.left sonLayerCurrent = sonLayerCurrent.next # Try to access the right son if there is if fatherLayerCurrent.right != None: if sonLayerHead == None: sonLayerHead = fatherLayerCurrent.right sonLayerCurrent = sonLayerHead else: sonLayerCurrent.next = fatherLayerCurrent.right sonLayerCurrent = sonLayerCurrent.next fatherLayerCurrent = fatherLayerCurrent.next # Prepare to move down to the next layer. fatherLayerCurrent = sonLayerHead sonLayerHead =None return |
The posts in Leetcode’s discussion section is less helpful and misleading sometimes.
I am not even sure if my “ACCEPTED” code is really correct considering the fact the test cases are biased and size is relative small…