116. 各ノードの次の右側のノード ポインタ階層のトラバーサルを埋める

問題: 116. 各ノードの右隣のノード ポインターを設定する

記事ディレクトリ

一連の考え

まず、完全なバイナリ ツリーを階層的に走査し、ノードの数を記録し (各層の最後のノードが指すため、現在の層番号はノード番号から計算できます)、それをスタックにプッシュし、スタック上で操作しnextますNULL。 。

問題解決法

int h = static_cast<int>(log2(cnt ))+1 ; // 現在のノード番号に従って、現在のノードが位置するレイヤーの数と
int lastNode = pow(2, h) - 1; 各レイヤーの最後のノードの番号を計算します

  1. バイナリ ツリーを階層的にトラバースし、ノードの数を記録し、階層トラバースの順序でノードをスタックにプッシュします。
  2. 最後のノードの番号は cnt であり、スタックにアクセスし、現在のノードが配置されている層の数を計算し、現在の層の最後のノードの番号を計算します。現在の cnt と一致する場合、それを意味します。現在のレイヤーの最後のノードです。cur->next = NULL ;それ以外の場合は、cur->next = pre ;
  3. ノード番号cnt--

コード

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) ; 
            }

        }


    }
};

おすすめ

転載: blog.csdn.net/qq_41661809/article/details/131919952