lc-go/solutions/8/q865/solution.go

36 lines
680 B
Go

// Package q865 implements a solution for https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/
package q865
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func search(node *TreeNode, depth int) (*TreeNode, int) {
if node == nil {
return nil, 0
}
if node.Left == nil && node.Right == nil {
return node, depth
}
ln, ld := search(node.Left, depth+1)
rn, rd := search(node.Right, depth+1)
switch {
case ld == rd:
return node, ld
case ld < rd:
return rn, rd
default:
return ln, ld
}
}
func subtreeWithAllDeepest(root *TreeNode) *TreeNode {
node, _ := search(root, 1)
return node
}
var _ = subtreeWithAllDeepest