1. 程式人生 > >Populating Next Right Pointers in Each Node II - LeetCode

Populating Next Right Pointers in Each Node II - LeetCode

front code ret pointers 一模一樣 href ati {} leet

目錄

  • 題目鏈接
  • 註意點
  • 解法
  • 小結

題目鏈接

Populating Next Right Pointers in Each Node II

註意點

  • 不要訪問空結點
  • 不是完美二叉樹

解法

解法一:遞歸,DFS。因為不是完美二叉樹所以子樹有可能殘缺,故需要平行掃描父節點同層的節點,找到他們的左右子節點。然後右節點就是找到的節點,左節點就是如果右節點存在就選右節點否則選找到的節點

/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* left;
    Node* right;
    Node* next;

    Node() {}

    Node(int _val, Node* _left, Node* _right, Node* _next) {
        val = _val;
        left = _left;
        right = _right;
        next = _next;
    }
};
*/
class Solution {
public:
    Node* connect(Node* root) {
        if(!root) return NULL;
        Node* p = root->next;
        while (p) 
        {
            if (p->left) 
            {
                p = p->left;
                break;
            }
            if (p->right) 
            {
                p = p->right;
                break;
            }
            p = p->next;
        }
        if(root->right) root->right->next = p;
        if(root->left) root->left->next = root->right ? root->right : p; 
        connect(root->right);
        connect(root->left);
        return root;
    }
};

技術分享圖片

解法二:非遞歸。和Populating Next Right Pointers in Each Node - LeetCode一模一樣

/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* left;
    Node* right;
    Node* next;

    Node() {}

    Node(int _val, Node* _left, Node* _right, Node* _next) {
        val = _val;
        left = _left;
        right = _right;
        next = _next;
    }
};
*/
class Solution {
public:
    Node* connect(Node* root) {
        if(!root) return NULL;
        queue<Node*> q;
        q.push(root);
        while(!q.empty())
        {
            int size = q.size();
            for(int i = 0;i < size;i++)
            {
                Node* temp = q.front();q.pop();
                if(i != size-1) temp->next = q.front();
                if(temp->left) q.push(temp->left);
                if(temp->right) q.push(temp->right);
            }
        }
        return root;
    }
};

技術分享圖片

小結

  • 只要是遍歷都有遞歸和非遞歸兩種寫法

Populating Next Right Pointers in Each Node II - LeetCode