116. Populating Next Right Pointers in Each Node【力扣】

题意理解

填充树结点的右结点。

问题分析

递归,子结构是root-left-right

如果结点为空,返回结点;

根结点默认已连接好,左结点的下一个结点是右结点,右结点的下一个节点是根结点的下一个结点的左结点。

其他

链接

    Node* connect(Node* root) {
        if(!root)
            return root;
        if (root -> left)    //左结点存在
        {
            root -> left -> next = root -> right;    //左结点的下一个结点是右结点
        }
        if (root -> right)    //右结点存在
        {
            if (root -> next)    //根节点的下一个结点是否存在
            {
                root -> right -> next = root -> next -> left;    //右结点的下一个结点是根结点的下一个结点的左结点
            }
            else
            {
                root -> right -> next = NULL;    //右结点的下一个结点是空
            }
        }           
        connect(root -> left);    //递归连接左子树
        connect(root -> right);    //递归连接右子树
        return root;
    }

猜你喜欢

转载自blog.csdn.net/xiexie1357/article/details/88221124
今日推荐