Easy understand and short solution


  • 0
    T
    class Solution {
    public:
    	void connect(TreeLinkNode *root) {
    		if (!root) return;
    		queue<TreeLinkNode*> q, p;
    		p.push(root);
    		while (!p.empty()){
    			q = p;
    			queue<TreeLinkNode*> empty;
    			swap(p, empty);
    			TreeLinkNode *t = q.front();
    			t->next = NULL;
    			while (!q.empty()){
    				t = q.front();
    				q.pop();
    				if (t->right) p.push(t->right);
    				if (t->left) p.push(t->left);
    				if (!q.empty()) q.front()->next = t;
    			}
    		}
    	}
    };

  • 0
    7

    level order traversal is not constant space, since use a queue with space O(some n)


Log in to reply
 

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