Leetcode Note: Go - Merge Two Binary Trees

Merge Two Binary Trees - LeetCode
https://leetcode.com/problems/merge-two-binary-trees/

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

所感

  • 2つ の binary tree をマージして return する

回答

Merge Two Binary Trees - LeetCode
https://leetcode.com/problems/merge-two-binary-trees/solution/

golang solution - LeetCode Discuss
https://leetcode.com/problems/merge-two-binary-trees/discuss/492357/golang-solution

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func mergeTrees(t1 *TreeNode, t2 *TreeNode) *TreeNode {
    // if one of t1 and t2 is nil, return the other
    if t1 == nil {
        return t2
    }
    if t2 == nil {
        return t1
    }
    // merge t1 and t2
    root := &TreeNode{Val: t1.Val + t2.Val}
    // recursion
    root.Left = mergeTrees(t1.Left, t2.Left)
    root.Right = mergeTrees(t1.Right, t2.Right)
    return root
}
  • 再帰で走査しつつ 2つ の binary tree それぞれの Node が存在すれば Value を加算した Node として return する