1. 程式人生 > >【LeetCode】117. 填充同一層的兄弟節點 II 結題報告 (C++)

【LeetCode】117. 填充同一層的兄弟節點 II 結題報告 (C++)

題目描述:

給定一個二叉樹

struct TreeLinkNode {   TreeLinkNode *left;   TreeLinkNode *right;   TreeLinkNode *next; } 填充它的每個 next 指標,讓這個指標指向其下一個右側節點。如果找不到下一個右側節點,則將 next 指標設定為 NULL。

初始狀態下,所有 next 指標都被設定為 NULL。

說明:

你只能使用額外常數空間。 使用遞迴解題也符合要求,本題中遞迴程式佔用的棧空間不算做額外的空間複雜度。 示例:

給定二叉樹,

     1    /  \   2    3  / \    \ 4   5    7 呼叫你的函式後,該二叉樹變為:

     1 -> NULL    /  \   2 -> 3 -> NULL  / \    \ 4-> 5 -> 7 -> NULL

解題方案:

與上一題116一模一樣了。。

/**
 * 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:
    queue<TreeLinkNode *> q1, q2;
    void connect(TreeLinkNode *root) {
        if(!root)
            return;
        q1.push(root);
        while(!q1.empty() || !q2.empty())
            if(!q1.empty()){ 
                while(!q1.empty()){
                    TreeLinkNode* tmp = q1.front();
                    q1.pop();
                    if(tmp->left)
                        q2.push(tmp->left);
                    if(tmp->right)
                        q2.push(tmp->right);
                    if(!q1.empty())
                        tmp->next = q1.front();
                }
            }
            else{   
                while(!q2.empty()){
                    TreeLinkNode* tmp = q2.front();
                    q2.pop();
                    if(tmp->left)
                        q1.push(tmp->left);
                    if(tmp->right)
                        q1.push(tmp->right);
                    if(!q2.empty())
                        tmp->next = q2.front();
                }
            }

    }
};