Populating Next Right Pointers in Each Node - LeetCode指針
解法一:遞歸,DFS。由於是完美二叉樹因此左子結點的next指針能夠直接指向其右子節點,對於其右子節點的處理方法是,判斷其父節點的next是否爲空,若不爲空,則指向其next指針指向的節點的左子結點,若爲空則指向NULL。code
/* // 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; if(root->left) { root->left->next = root->right; if(root->next) root->right->next = root->next->left; } connect(root->left); connect(root->right); return root; } };
解法二:非遞歸。程序遍歷每層的節點都按順序加入queue中,而每當從queue中取出一個元素時,將其next指針指向queue中下一個節點便可。blog
/* // 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; } };