(Frankly, this topic touched me, let me this novice programmer experience the beauty of logic )
Original title address: https://oj.leetcode.com/problems/populating-next-right-pointers-in-each-node/
Test instructions
1 / 2 3 /\ / 4 5 6 7
Into:
1, NULL / 2, 3, null /\ / 4->5->6->7, NULL
Problem-Solving ideas: This topic fully shows the macro and micro perfect in the details out of the concrete process.
1) Seeing a two-fork tree, we think of the idea of using recursion.
2) Note the details beyond recursion: Formal These details complete the actual logical solution
Let's take number 2nd as an example: in order to reproduce next node, only two microscopic cases need to be processed:
Case 1:2, 3:
Solution:root.left.next = Root.right
Case 2:2, 5-6:
Solution:root.right.next = Root.next.left if root.next else None
2-3 / \ / 4->5->6
#Definition for a binary tree node#class TreeNode:#def __init__ (self, x):#self.val = x#self.left = None#self.right = None#Self.next = NoneclassSolution:#@param root, a tree node #@return Nothing defConnect (self, root):ifRoot andRoot.left:root.left.next=root.right Root.right.next= Root.next.leftifRoot.nextElseNone self.connect (root.left) self.connect (root.right)
Reference acknowledgement: On the basis of [1], it highlights the dual processing of details.
[1] http://www.cnblogs.com/zuoyuan/p/3745170.html
[Leetcode] Populating Next right pointers in each Node @ Python [Logic Dynamics]