Leetcode 116. 填充同一层的兄弟节点 C++

题目描述

在这里插入图片描述

思路

本题是一个很典型的题,采用的方法就是树的层序历遍。通过一个队列控制,每次循环处理一层的节点,下一次处理下一层的节点。关于树的层序历遍可以参看另外两个题,可以有更深的认识。二叉树的层次遍历二叉树的锯齿形层次遍历.

解答

/**
 * 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/84470526
今日推荐