LeetCode in Kotlin

2641. Cousins in Binary Tree II

Medium

Given the root of a binary tree, replace the value of each node in the tree with the sum of all its cousins’ values.

Two nodes of a binary tree are cousins if they have the same depth with different parents.

Return the root of the modified tree.

Note that the depth of a node is the number of edges in the path from the root node to it.

Example 1:

Input: root = [5,4,9,1,10,null,7]

Output: [0,0,0,7,7,null,11]

Explanation: The diagram above shows the initial binary tree and the binary tree after changing the value of each node.

Example 2:

Input: root = [3,1,2]

Output: [0,0,0]

Explanation: The diagram above shows the initial binary tree and the binary tree after changing the value of each node.

Constraints:

Solution

import com_github_leetcode.TreeNode

/*
 * Example:
 * var ti = TreeNode(5)
 * var v = ti.`val`
 * Definition for a binary tree node.
 * class TreeNode(var `val`: Int) {
 *     var left: TreeNode? = null
 *     var right: TreeNode? = null
 * }
 */
class Solution {
    private var horizontalSum: MutableList<Int?>? = null

    private fun traverse(root: TreeNode?, depth: Int) {
        if (root == null) {
            return
        }
        if (depth < horizontalSum!!.size) {
            horizontalSum!![depth] = horizontalSum!![depth]!! + root.`val`
        } else {
            horizontalSum!!.add(root.`val`)
        }
        traverse(root.left, depth + 1)
        traverse(root.right, depth + 1)
    }

    private fun traverse1(root: TreeNode?, depth: Int) {
        if (root == null) {
            return
        }
        if (depth > 0) {
            var sum = 0
            if (root.left != null) {
                sum += root.left!!.`val`
            }
            if (root.right != null) {
                sum += root.right!!.`val`
            }
            if (root.left != null) {
                root.left!!.`val` = horizontalSum!![depth + 1]!! - sum
            }
            if (root.right != null) {
                root.right!!.`val` = horizontalSum!![depth + 1]!! - sum
            }
        }
        traverse1(root.left, depth + 1)
        traverse1(root.right, depth + 1)
    }

    fun replaceValueInTree(root: TreeNode?): TreeNode {
        horizontalSum = ArrayList()
        root!!.`val` = 0
        if (root.left != null) {
            root.left!!.`val` = 0
        }
        if (root.right != null) {
            root.right!!.`val` = 0
        }
        traverse(root, 0)
        traverse1(root, 0)
        return root
    }
}