117. 填充同一层的兄弟节点 II C++

题目描述

在这里插入图片描述

说明

本题和第116题竟然可以采用同样的程序通过,也是有点搞笑。本题的差别,不过是少了一个完全二叉树的条件,但是使用层序历遍的思想,根本不需要考虑这些限制条件。

解答

/**
 * 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) return;
        queue<TreeLinkNode*> q;
        q.push(root);
        while(!q.empty())
        {
            auto size = q.size();
            TreeLinkNode* temp = q.front();
            q.pop();
            
            while(size--)
            {
                if(temp->left) q.push(temp->left);
                if(temp->right) q.push(temp->right);
                
                if(0 == size) temp->next=NULL;
                else
                {
                    TreeLinkNode* cur = q.front();
                    q.pop();
                    temp->next = cur;
                    temp=cur;
                }
                
            }
        }
    }
};

猜你喜欢

转载自blog.csdn.net/yuanliang861/article/details/84476443