首页 > 代码库 > Leetcode 116. Populating next right pointers in each node I and II

Leetcode 116. Populating next right pointers in each node I and II

题目1:

Given a binary tree

    struct TreeLinkNode {
      TreeLinkNode *left;
      TreeLinkNode *right;
      TreeLinkNode *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.

Note:

  • You may only use constant extra space.
  • You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).

For example,
Given the following perfect binary tree,

         1
       /        2    3
     / \  /     4  5  6  7

After calling your function, the tree should look like:

         1 -> NULL
       /        2 -> 3 -> NULL
     / \  /     4->5->6->7 -> NULL

 题目2:

Follow up for problem "Populating Next Right Pointers in Each Node".

What if the given tree could be any binary tree? Would your previous solution still work?

Note:

  • You may only use constant extra space.

For example,
Given the following binary tree,

         1
       /        2    3
     / \        4   5    7

After calling your function, the tree should look like:

         1 -> NULL
       /        2 -> 3 -> NULL
     / \        4-> 5 -> 7 -> NULL


我们可以用类似level order traversal 以及 level zigzag traversa 的方法来直接解决这个更general的第二题l。本题只不过在输出每层的时候把本层的node从左向右用.next连起来。

 1 # Definition for binary tree with next pointer.
 2 # class TreeLinkNode:
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.left = None
 6 #         self.right = None
 7 #         self.next = None
 8 
 9 class Solution:
10     # @param root, a tree link node
11     # @return nothing
12     def connect(self, root):
13         if not root:
14             return
15         queue = [root]
16         while queue:
17             level = []
18             size = len(queue)
19             for i in range(size):
20                 node = queue.pop(0)
21                 level.append(node)
22                 if node.left:
23                     queue.append(node.left)
24                 if node.right:
25                     queue.append(node.right)
26             
27             for i in range(len(level)-1):
28                 level[i].next = level[i+1]
29             level[-1].next = None
30         
31         return

 

Leetcode 116. Populating next right pointers in each node I and II