Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save CollinShoop/ed49e4034babc8aa619d04552abaa9d8 to your computer and use it in GitHub Desktop.
Save CollinShoop/ed49e4034babc8aa619d04552abaa9d8 to your computer and use it in GitHub Desktop.
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func findLeaves(root *TreeNode) [][]int {
leaves := [][]int{}
leaf := func(depth, v int) {
if len(leaves) - 1 < depth {
leaves = append(leaves, []int{v})
} else {
leaves[depth] = append(leaves[depth], v)
}
}
var traverse func(root *TreeNode, depth int) int /*max depth*/
traverse = func(root *TreeNode, depth int) int {
if root == nil {
return depth-1
}
if root.Left == nil && root.Right == nil {
leaf(0, root.Val)
return depth
}
dl := traverse(root.Left, depth+1)
dr := traverse(root.Right, depth+1)
// assign max depth to dl
if dr > dl {
dl = dr
}
// add leaf at depth of the max - current
leaf(dl - depth, root.Val)
return dl
}
_ = traverse(root, 0)
return leaves
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment