116.PopulatingNextRightPointersinEachNode

你快乐吗?

Posted by bbkgl on September 26, 2019

116. Populating Next Right Pointers in Each Node

C++,dfs深搜解决。

题意看了好久才看懂,其实就是将每一层的点都连接起来。每个结点的next指针都指向右边的结点,这样分两种情况:

  • 如果右边结点是亲兄弟结点,则在遍历到父节点的时候就root->left->next = root->right;
  • 如果右边结点是堂兄弟结点,则在遍历到父节点的时候(此时父节点的next指针已经指向了右边的兄弟节点),通过父节点的next指针与右边结点相接: root->right->next = root->next->left;

代码如下:

class Solution {
public:
    Node* connect(Node* root) {
        if (!root) return NULL;
        if (root->left) root->left->next = root->right;
        if (root->next && root->right)
            root->right->next = root->next->left;
        connect(root->left);
        connect(root->right);
        return root;
    }
};