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

题目

给定一个二叉树
这里写图片描述
填充它的每个 next指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL
初始状态下,所有 next 指针都被设置为 NULL
说明:
1. 你只能使用额外常数空间。
2. 使用递归解题也符合要求,本题中递归程序占用的栈空间不算做额外的空间复杂度。
示例:
给定二叉树,
这里写图片描述
调用你的函数后,该二叉树变为:
这里写图片描述

代码

/**
 * 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;
        TreeLinkNode *node=root,*tmp=root;
        while(root){
            if(root->left&&root->right)
                root->left->next=root->right;
            else if(root->left==NULL&&root->right==NULL){
                root=root->next;
                continue;
            }
            tmp=root->next;
            while(tmp&&tmp->left==NULL&&tmp->right==NULL) tmp=tmp->next;
            if(tmp!=NULL){
                if(root->right!=NULL)
                    root->right->next=tmp->left!=NULL?tmp->left:tmp->right;
                else if(root->left!=NULL)
                    root->left->next=tmp->left!=NULL?tmp->left:tmp->right;
            }
            root=tmp;
        }
        while(node&&node->left==NULL&&node->right==NULL) node=node->next;
        if(node==NULL) return;
        else if(node->left)
            connect(node->left);
        else
            connect(node->right);
    }
};

猜你喜欢

转载自blog.csdn.net/lv1224/article/details/80196842