题目描述

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;
                }
                
            }
        }
    }
};

相关文章:

  • 2022-01-01
  • 2021-10-20
  • 2021-11-30
  • 2021-11-30
  • 2021-04-16
  • 2021-07-06
  • 2021-05-25
  • 2021-11-30
猜你喜欢
  • 2021-04-02
  • 2021-06-15
  • 2021-09-29
  • 2021-08-29
  • 2021-11-30
  • 2021-08-21
相关资源
相似解决方案