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

每次递归的输入,第k层的起始结点【通过next访问第k层其他结点】

/**
 * 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;
        TreeLinkNode *p=NULL,*q=NULL;
        while(root){
            if(root->left){
                if(!p) p=root->left;
                if(!q) q=root->left;
                else q->next=root->left,q=q->next;
            }
            if(root->right){
                if(!p) p=root->right;
                if(!q) q=root->right;
                else q->next=root->right,q=q->next;
            }
            root=root->next;
        }
        connect(p);
    }
};

猜你喜欢

转载自blog.csdn.net/bendaai/article/details/80601090