O(n) complexity O(1) space Iterative C Solution


  • 0
    W

    Easy to understand, but containing duplicate operations when visiting the left child and the right child. Any other way better?

    void connect(struct TreeLinkNode *root)
    {
      struct TreeLinkNode *fa, *p, *first;
      for (fa = root; fa; fa = first)
      {
        first = p = NULL;
        for (; fa; fa = fa->next)
        {
          if (fa->left)
            if (p) p->next = fa->left, p = p->next;
            else first = p = fa->left;
          if (fa->right)
            if (p) p->next = fa->right, p = p->next;
            else first = p = fa->right;
        }
      }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.