Cpp: simplest solution using recursion


  • 0
    C

    Since we can always find value of next pointer for children 'left' and 'right' on current node or current->next node, this makes solution very easy and simple recursion can be used to solve the problem.

    /**
     * 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;
            if(root->left){
                root->left->next=root->right;
                if(root->next)
                    root->right->next=root->next->left;
            }
            connect(root->left);
            connect(root->right);
        }
    };
    
    
    

Log in to reply
 

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