题目:
给定一个完美二叉树,其所有叶子节点都在同一层,每个父节点都有两个子节点。二叉树定义如下:
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。
初始状态下,所有 next 指针都被设置为 NULL。
示例:
AC代码
class Solution {
public:
Node* store[100] = {NULL};
Node* bianli(Node* &nodes,int h){
if(nodes == NULL)
return NULL;
nodes->right = bianli(nodes->right,h + 1);
nodes->left = bianli(nodes->left,h + 1);
if(store[h] == NULL){
nodes->next = NULL;
store[h] = nodes;
}
else{
nodes->next = store[h];
store[h] = nodes;
}
return nodes;
}
Node* connect(Node* root) {
if(root == NULL)
return NULL;
return bianli(root,1);
}
};