总的来说,虽然知道大部分二叉树的题都能用递归来解决,但是有的时候很难想到,这个题又做复杂了。
这题我用了队列套pair层次遍历,然后又用vector套pair保存遍历的结果,最后才循环一遍改变next指针。
反正写的是最麻烦的,当然越麻烦的越容易看懂,还要记得二叉树千万不要用到最后一层的后面一层,即使不是递归也不行,递归更不行。
代码:
/**
* Definition for binary tree with next pointer.
* struct TreeLinkNode {
* int val;
* TreeLinkNode *left, *right, *next;
* TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
* };
*/
class Solution {
public:
void connect(TreeLinkNode *root) {
if(!root)
return ;
queue<pair<TreeLinkNode*,int>> q;
q.push(make_pair(root,0));
vector<pair<TreeLinkNode*,int>> v;
while(!q.empty()){
pair<TreeLinkNode*,int> tem=q.front();
v.push_back(tem);
q.pop();
TreeLinkNode* tree=tem.first;
int height=tem.second;
if(tree->left)
q.push(make_pair(tree->left,height+1));
if(tree->right)
q.push(make_pair(tree->right,height+1));
}
for(int i=0;i<v.size()-1;i++){
pair<TreeLinkNode*,int> tem=v[i];
TreeLinkNode* tree=tem.first;
int height=tem.second;
pair<TreeLinkNode*,int> tem1=v[i+1];
TreeLinkNode* tree1=tem1.first;
int height1=tem1.second;
if(height1==height)
tree->next=tree1;
}
}
};
另外这里层次遍历的非递归做法也写麻烦了,这里有个取队列最后一个元素的函数很关键,每次更新标记,此标记为接下来一层数字的最后一个元素,
至于更新原理很好理解,上一次到达了尾部,此层也就到了尾部。
代码:
/**
* Definition for binary tree with next pointer.
* struct TreeLinkNode {
* int val;
* TreeLinkNode *left, *right, *next;
* TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
* };
*/
class Solution {
public:
void connect(TreeLinkNode *root) {
if(!root)
return ;
queue<TreeLinkNode*> q;
q.push(root);
TreeLinkNode *tail=root;
while(!q.empty()){
TreeLinkNode* tem=q.front();
q.pop();
if(tem->left)
q.push(tem->left);
if(tem->right)
q.push(tem->right);
if(tem==tail)
tail=q.back();
else
tem->next=q.front();
}
}
};
下面是最简单的递归:
其实也很好理解,如果此节点的next指针不为NULL,那么它的右子节点肯定指向它右边节点的左子节点,不明白可以画图,很清晰:
代码:
/**
* Definition for binary tree with next pointer.
* struct TreeLinkNode {
* int val;
* TreeLinkNode *left, *right, *next;
* TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
* };
*/
class Solution {
public:
void connect(TreeLinkNode *root) {
if(!root)
return ;
if(root->left&&root->right)
root->left->next=root->right;
if(root->next&&root->right)
root->right->next=root->next->left;
connect(root->left);
connect(root->right);
}
};