2019-12-27
08:52:23
解法1:DFS 递归解决
/* // Definition for a Node. class Node { public: int val; Node* left; Node* right; Node* next; Node() : val(0), left(NULL), right(NULL), next(NULL) {} Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {} Node(int _val, Node* _left, Node* _right, Node* _next) : val(_val), left(_left), right(_right), next(_next) {} }; */ class Solution { public: int flag = 1; Node* connect(Node* root) { if(!root) return NULL; if(flag){ root->next = NULL; flag = 0; } if(!(root->left)){ return root; } else root->left->next = root->right; if(root->next){ root->right->next = root->next->left; }else{ root->right->next = nullptr; } connect(root->left); connect(root->right); return root; } };
解法2: BFS 迭代
/* // Definition for a Node. class Node { public: int val; Node* left; Node* right; Node* next; Node() : val(0), left(NULL), right(NULL), next(NULL) {} Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {} Node(int _val, Node* _left, Node* _right, Node* _next) : val(_val), left(_left), right(_right), next(_next) {} }; */ class Solution { public: Node* connect(Node* root) { Node *now = root; while(now != NULL){ Node *temp = now; while(temp!=NULL){ if(temp->left != NULL){ temp->left->next = temp->right; } if(temp->right != NULL && temp->next != NULL){ temp->right->next = temp->next->left; } temp = temp->next; } now = now->left; } return root; } };