题目链接
Populating Next Right Pointers in Each Node II
注意点
- 不要访问空结点
- 不是完美二叉树
解法
解法一:递归,DFS。因为不是完美二叉树所以子树有可能残缺,故需要平行扫描父节点同层的节点,找到他们的左右子节点。然后右节点就是找到的节点,左节点就是如果右节点存在就选右节点否则选找到的节点
/*
// 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一模一样
/*
// 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;
}
};
小结
- 只要是遍历都有递归和非递归两种写法