Problem: 116. 填充每个节点的下一个右侧节点指针
思路
首先层次遍历一下满二叉树并记录结点个数(由结点编号可以计算出当前所在的层数,由于每层的最后一个结点的
next
是指向NULL
),将其压入栈,然后对栈进行操作。
解题方法
int h = static_cast<int>(log2(cnt ))+1 ;
// 根据当前结点编号,计算当前结点所在的层数,
int lastNode = pow(2, h) - 1;
每层的最后一个结点的编号
- 层次遍历二叉树,并记录结点个数,将节点按照层次遍历的顺序压入栈
- 最后一个结点的编号是cnt ,访问栈,计算当前结点所在的层数,计算当前层数最后一个结点的编号,如果和当前cnt一致,说明是当前层最后一个结点
cur->next = NULL ;
否则cur->next = pre ;
- 结点编号
cnt--
Code
class Solution {
public:
stack<Node*> node_stack ;
int cnt = 0 ;
Node* connect(Node* root) {
// 层次遍历
// Node *pre = NULL;
level_traversal(root) ;
Node *pre = NULL;
// int h = static_cast<int>(log2(cnt + 1)); ; //满二叉的树高
cout<<cnt <<endl ;
while(!node_stack.empty()){
Node* cur = node_stack.top() ;
int h = static_cast<int>(log2(cnt ))+1 ; //树高
node_stack.pop() ;
int lastNode = pow(2, h) - 1;
if(cnt == lastNode) {
cur->next = NULL ;
}else{
cur->next = pre ;
}
pre = cur ;
cnt-- ; // 结点编号减去1
}
return root ;
}
void level_traversal( Node * root ) {
// 层次遍历
if(!root){
return ;
}
queue<Node*> q ;
q.push(root) ;
Node* current = q.front() ;
while(!q.empty() ){
cnt++ ;
current = q.front() ;
q.pop() ;
node_stack.push(current) ;
// cout<<"cur " <<current->val <<endl ;
if(current->left ) {
q.push(current->left) ;
}
if(current->right) {
q.push(current->right) ;
}
}
}
};