Golang concise 9ms solution


  • 0

    Beats 100% other solutions so far:)
    Just using breadth first search of the whole tree. Each node is stored in a queue and we use start and end indexes to iterate nodes one depth level by one.

    func maxDepth(root *TreeNode) int {
    	if root == nil {
    		return 0
    	}
    	que := []*TreeNode{root}
    	depth := 1
    	start, end := 0, 1
    
    	for {
    		numOfChildren := 0
    		for i := start; i < end; i++ {
    			node := que[i]
    			if node.Left != nil {
    				que = append(que, node.Left)
    				numOfChildren++
    			}
    			if node.Right != nil {
    				que = append(que, node.Right)
    				numOfChildren++
    			}
    		}
    		if numOfChildren == 0 {
    			break
    		}
    
    		depth++
    		start = end
    		end = end + numOfChildren
    	}
    
    	return depth
    }
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.