当前位置:网站首页>Sword finger offer 32: print binary tree from top to bottom

Sword finger offer 32: print binary tree from top to bottom

2022-06-11 05:46:00 swindler.

The finger of the sword Offer 32: Print binary tree from top to bottom

Breadth first traversal

class solution {
    
 func levelOrder(_ root: TreeNode?) -> [[Int]] {
    
guard let rootVal = root else {
    
return [[Int]]()

var result = [[Int]](()// Two dimensional array returned from the result 
var queue = [TreeNode]()// queue 
queue.append(rootVal)

var curBlancecount = 1 // Record the remaining nodes to be printed in the current layer 
var nextCount = 0 // Record the nodes to be recorded and printed on the next layer 
var tempArray = [Int]() // One dimension of temporary two-dimensional array , Used to record each layer 

while !queue.isEmpty{
    
let tempNode = queue.first
if let leftNode = tempNode?.left{
    
	nextCount += 1
	queue.append(leftNode)
}
if let rightNode = tempNode?.left{
    
	nextCount += 1 
	queue.append(rightNode)
}
queue.removeFirst()
tempArray.append(tempNode!.val)
curBalancecount -= 1
if curBalancecount == 0{
    
result.append(tempArray)
tempArray.removefromAll()
curBalancecount = nextCount
nextCount = 0
}
}
return result
 }
}
原网站

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