Created
March 4, 2022 15:03
-
-
Save CollinShoop/ed49e4034babc8aa619d04552abaa9d8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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