Populating Next Right Pointers in Each Node IInode
解法一:遞歸,DFS。由於不是完美二叉樹因此子樹有可能殘缺,故須要平行掃描父節點同層的節點,找到他們的左右子節點。而後右節點就是找到的節點,左節點就是若是右節點存在就選右節點不然選找到的節點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; 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如出一轍htm
/* // 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; } };