Leetcode Note: Go - Leaf Similar Trees

Leaf-Similar Trees - LeetCode
https://leetcode.com/problems/leaf-similar-trees/

  • Go 言語で取り組んだメモ

所感

  • 与えられた Tree Nodes を走査して leaf similar だったら true を return する
  • leaf similar: node 値の順序が同じであること

回答

Leaf-Similar Trees - LeetCode
https://leetcode.com/problems/leaf-similar-trees/solution/

Go solution simple hehe - LeetCode Discuss
https://leetcode.com/problems/leaf-similar-trees/discuss/2290235/Go-solution-simple-hehe

func leafSimilar(root1 *TreeNode, root2 *TreeNode) bool {
    var arr1, arr2 []int
    
    dfs(root1, &arr1)
    dfs(root2, &arr2)
    
    if len(arr1) != len(arr2) {
        return false
    }
    
    for i := 0; i < len(arr1); i++ {
        if arr1[i] != arr2[i] {
            return false
        }   
    }
    
    return true
}

func dfs(root *TreeNode, arr *[]int) {
    if root == nil {
        return 
    }
    
    if root.Left == nil && root.Right == nil {
        *arr = append(*arr, root.Val)
    }
    
    dfs(root.Left, arr)
    dfs(root.Right, arr)
}