leetcode-116. Populating Next Right Pointers in Each Node

时间:2022-12-28 21:43:08

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

思路:起初觉得是个很难的题,但是后来发现了Note里面的限制(给定二叉树是完全二叉树),所以简单好多,只需要逐层处理即可。

Accepted Code:
 1 /**
 2  * Definition for binary tree with next pointer.
 3  * struct TreeLinkNode {
 4  *  int val;
 5  *  TreeLinkNode *left, *right, *next;
 6  *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     void connect(TreeLinkNode *root) {
12         if(root==nullptr)
13         return;
14         TreeLinkNode* pre=root;
15         TreeLinkNode* cur=nullptr;
16         while(pre->left)
17         {
18             cur=pre;
19             while(cur)
20             {
21                 cur->left->next=cur->right;
22                 if(cur->next)
23                 {
24                     cur->right->next=cur->next->left;
25                     cur=cur->next;
26                 }else
27                 break;
28             }
29             pre=pre->left;
30         }
31     }
32 };