[Leetcode] Populating Next right pointers in each Node @ Python [Logic Dynamics]

Source: Internet
Author: User

(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]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.