LeetCode-in-Java

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;
import java.util.ArrayList;
import java.util.List;

/*
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
public class Solution {
    private List<Integer> horizontalSum;

    private void traverse(TreeNode root, int depth) {
        if (root == null) {
            return;
        }
        if (depth < horizontalSum.size()) {
            horizontalSum.set(depth, horizontalSum.get(depth) + root.val);
        } else {
            horizontalSum.add(root.val);
        }
        traverse(root.left, depth + 1);
        traverse(root.right, depth + 1);
    }

    private void traverse1(TreeNode root, int depth) {
        if (root == null) {
            return;
        }
        if (depth > 0) {
            int 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.get(depth + 1) - sum;
            }
            if (root.right != null) {
                root.right.val = horizontalSum.get(depth + 1) - sum;
            }
        }
        traverse1(root.left, depth + 1);
        traverse1(root.right, depth + 1);
    }

    public TreeNode replaceValueInTree(TreeNode root) {
        horizontalSum = new 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;
    }
}