LeetCode-Populating Next Right Pointers in Each Node
有点类似于层级遍历,用两个数组保存上下两层的结点即可!
同样的代码两道题目都可以过!
1 /** 2 * Definition for binary tree with next pointer. 3 * struct TreeLinkNode { 4 * int val; 5 * TreeLinkNode *left, *right, *next; 6 * TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 void connect(TreeLinkNode *root) { 12 // Start typing your C/C++ solution below 13 // DO NOT write int main() function 14 vector<vector<TreeLinkNode*> > level(2); 15 int pre = 0; 16 int cur = 1; 17 if (root == NULL) { 18 return; 19 } 20 level[cur].push_back(root); 21 while (!level[cur].empty()) { 22 pre = !pre; 23 cur = !cur; 24 level[cur].clear(); 25 for (size_t i = 0; i < level[pre].size(); ++i) { 26 if (i == level[pre].size() - 1) { 27 level[pre][i]->next = NULL; 28 } 29 else { 30 level[pre][i]->next = level[pre][i + 1]; 31 } 32 if (level[pre][i]->left != NULL) { 33 level[cur].push_back(level[pre][i]->left); 34 } 35 if (level[pre][i]->right != NULL) { 36 level[cur].push_back(level[pre][i]->right); 37 } 38 } 39 } 40 } 41 };