[LeetCode] Populating Next Right Pointers in Each Node

Given a binary tree

    struct TreeLinkNode {
      TreeLinkNode *left;
      TreeLinkNode *right;
      TreeLinkNode *next;
    }

Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.

Initially, all next pointers are set to NULL.

Note:

  • You may only use constant extra space.
  • You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).


1. BFS: use a queue to keep breadth-first traversal result

/**
 * 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) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        //breadth-first traversal
        queue<TreeLinkNode *> bfsq;
        int levelCnt=0;
        int level2=0;
        
        if(root==NULL) return;
        bfsq.push(root);
        levelCnt++;
        TreeLinkNode *prevList=NULL;
        TreeLinkNode *topS=NULL;
        
        while(!bfsq.empty()) 
        {
            topS=bfsq.front();
            bfsq.pop();
            levelCnt--;
        
            if(topS->left!=NULL && topS->right!=NULL)
            {   
                bfsq.push(topS->left);
                level2++;
                bfsq.push(topS->right);
                level2++;
            }
            
            if(prevList!=NULL)
                prevList->next=topS;
            prevList=topS;
            
            if(levelCnt==0)
            {
                levelCnt=level2;
                level2=0;
                prevList=NULL;
            }
            
        }
    }
};

2. Recursion to save space: populating by level. node->right->next = node->next->left

class Solution {
public:
    void connect(TreeLinkNode *root) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        if(root==NULL || (root->left==NULL && root->right==NULL) ) 
            return;
        
        root->left->next=root->right;
        root->right->next=(root->next)? root->next->left:NULL;
        
        connect(root->left);
        connect(root->right);
    }
};




發佈了110 篇原創文章 · 獲贊 4 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章