当前位置:网站首页>[JS solution] leedcode 117 Populate the next right node pointer II for each node

[JS solution] leedcode 117 Populate the next right node pointer II for each node

2022-06-13 04:40:00 xiaozhangtxue

Subject requirements :

Given a binary tree

struct Node {
int val;
Node *left;
Node *right;
Node *next;
}

Fill in each of its next The pointer , Let this pointer point to its next right node . If the next right node cannot be found , Will next The pointer is set to NULL.
In the initial state , all next The pointer is set to NULL.

Example :

Input :root = [1,2,3,4,5,null,7]
Output :[1,#,2,3,#,4,5,7,#]
explain : A given binary tree is shown in figure A Shown , Your function should fill in every one of its next The pointer , To point to its next right node , Pictured B Shown . The serialized output is in sequence traversal order ( from next Pointer connection ),‘#’ Represents the end of each layer .

JS Code

var connect = function(root) {
    
    //  Deal with special situations 
    if (!root) return null
    //  Building hierarchically traversed arrays 
    let arr = [root]
    while(arr.length){
    
        let n  = arr.length
        for(let i=0;i<n;i++){
    
            //  Throw the current node 
            let curNode = arr.shift()
            //  If it is the last node, it points to null
            if(i===n-1) curNode.next=null
            //  If it's not the last node , Then point to the next node ( That is to say arr The first node in )
            else curNode.next= arr[0]
            //  Continue to traverse the left and right children 
            if(curNode.left!==null) arr.push(curNode.left)
            if(curNode.right!==null) arr.push(curNode.right)
        }
    }
    return root
};

Running results

 Insert picture description here

原网站

版权声明
本文为[xiaozhangtxue]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/164/202206130436334313.html