LeetCode116. Populating Next Right Pointers in Each Node(思路及python解法)

You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:

struct Node {
  int val;
  Node *left;
  Node *right;
  Node *next;
}

Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.

Initially, all next pointers are set to NULL.


注意保存下一层最左面的点,也就是next。

剩下就是判断当前点cur是否是这一层最右面的点。

总体还是比较简单的。

class Solution:
    def connect(self, root: 'Node') -> 'Node':
        if not root:return root
        cur = root
        next = root.left
        
        while cur.left:
            cur.left.next = cur.right
            if cur.next:
                cur.right.next=cur.next.left
                cur=cur.next
            else:
                cur=next
                next=cur.left
        return root

 

你可能感兴趣的:(Python,LeetCode)