LeetCode 116 Populating Next Right Pointers in Each Node

Given a binary tree

    struct TreeLinkNode {
      TreeLinkNode *left;
      TreeLinkNode *right;
      TreeLinkNode *next;
    }
  • 1
  • 2
  • 3
  • 4
  • 5

  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
  • 1
  • 2
  • 3
  • 4
  • 5

  After calling your function, the tree should look like:

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

题目大意

  给定一棵二叉树,有一个next指针,将它们的每一层链接起来。只能使用常量额外空间,树是一棵完美二叉树。 

解题思路

  将树的每一层节点用next串起来。这样每一层也会形成一个单链表。而每层的链表头,则是,根的左孩子,左孩子,左孩子。利用双循环,外层循环,沿着根的左孩子,一直向下。内层循环,负责将下一层的节点串起来。即,将自己右孩子放到左孩子的next上,而右孩子,则可通过自己的next指针,找到右邻居。 

我的思路,首先,先用循环把右侧的所有next指针设为NULL

                  然后使用两个指针,一个表示当前节点cur,另一个表示指向当前节点的所在层的第一个节点pre,保证可以处理完再移动到下一层。

                 然后,每一层负责处理下一层的next建立,所以要满足while(pre&&pre->next)

class Solution {
public:
    void connect(TreeLinkNode *root) {
        if(!root) return ;
        TreeLinkNode *cur=root;
        //多此一举的附初始值,但是会比较清楚
        while(cur){
            cur->next=NULL;
            cur=cur->right;
        }
        TreeLinkNode *prev=root;//保存的是当前处理的一层的第一个节点,为了能够处理完一层,移动到下一层
        cur=root;
        while(prev&&prev->left)
        {
            cur=prev;
            while(cur)
            {
                cur->left->next=cur->right;
                if(cur->next) cur->right->next=cur->next->left;
                cur=cur->next;
            }
            prev=prev->left;
            
        }
    }
    

猜你喜欢

转载自blog.csdn.net/momo_mo520/article/details/80385228