【一天一道LeetCode】#117. Populating Next Right Pointers in Each Node II

时间:2023-03-09 18:21:42
【一天一道LeetCode】#117. Populating Next Right Pointers in Each Node II

一天一道LeetCode

本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github

欢迎大家关注我的新浪微博,我的新浪微博

欢迎转载,转载请注明出处

(一)题目

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

(二)解题

参考:【一天一道LeetCode】#116. Populating Next Right Pointers in Each Node

没想到昨天做的解法直接把今天的题给解了。一模一样的代码,请跳转到上题的解题思路:

/**
 * Definition for binary tree with next pointer.
 * struct TreeLinkNode {
 *  int val;
 *  TreeLinkNode *left, *right, *next;
 *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
 * };
 */
class Solution {
public:
    void connect(TreeLinkNode *root) {
        if(root==NULL) return;
        queue<TreeLinkNode *> myque;
        myque.push(root);
        while(!myque.empty())
        {
            queue<TreeLinkNode *> temp_que;
            TreeLinkNode *pre = NULL;
            while(!myque.empty())
            {
                TreeLinkNode *temp = myque.front();
                myque.pop();
                if(pre==NULL) pre = temp;//相当于每一层的头节点
                else {
                    pre->next = temp;//用next指针连接每一层的节点
                    pre = temp;
                }
                if(temp->left!=NULL) temp_que.push(temp->left);//下一层
                if(temp->right!=NULL) temp_que.push(temp->right);//下一层
            }
            pre->next=NULL;//最后一个节点的next需要指向NULL
            myque=temp_que;//进入下一层操作
        }
    }
};