The binary tree --- print into multiple lines

Printing the binary tree in layers from top to bottom, from left to right with the output layer node. Each line of output layer.

Analysis: First, put the root node in the queue to be printed, before printing to save its child nodes in the queue,

It should have a list of the current storage node layer, there is a counter in mind how many nodes you want to print, how many nodes of the next layer.

/ * Function the TreeNode (X) { 
    this.val = X; 
    this.left = null; 
    this.right = null; 
} * / 
function the Print (PROOT) 
{ 
    // Write code here Wallpaper 
    const Queue = [], RES = []
     IF (PROOT === null ) {
         return RES 
    } 
    queue.push (PROOT) 
    the let nextLevel = 0 // number of the next layer node 
    the let toBePrinted =. 1 // this layer to be printed, how many nodes 
    let list = [ ] // storage node of each layer 
    the while (queue.length) { 
        const • pNode = queue.shift ()
        list.push(pNode.val)
        if(pNode.left!==null){
            queue.push(pNode.left)
            nextLevel++
        }
        if(pNode.right!==null){
            queue.push(pNode.right)
            nextLevel++
        }
        toBePrinted--
        if(toBePrinted==0){
            res.push(list)
            list=[]
            toBePrinted=nextLevel
            nextLevel=0
        }
    }
    return res
}

 

Guess you like

Origin www.cnblogs.com/mlebk/p/12632506.html