import java.util.ArrayList;
import java.util.List;
import java.util.function.ToIntFunction;
import java.util.stream.Collectors;
public class Test {
static class Node implements Cloneable {
int val;
Node left;
Node right;
public Node(int val, Node left, Node right) {
this.val = val;
this.left = left;
this.right = right;
}
@Override
protected Node clone() throws CloneNotSupportedException {
Node node = new Node(val, left == null ? null : left.clone(), right == null ? null : right.clone());
return node;
}
}
public static void main(String[] args) throws CloneNotSupportedException {
Node node1 = new Node(1, null, null);
Node node2 = new Node(2, node1, null);
Node node4 = new Node(4, null, null);
Node node6 = new Node(6, null, null);
Node node5 = new Node(5, node4, node6);
Node root = new Node(3, node2, node5);
updateNode(root.clone(), root);
System.out.println(root);
}
static List<Integer> gtList = new ArrayList();
public static void updateNode(Node root, Node currentNode) {
if (currentNode == null || root == null) {
return;
}
getNodesAverage(root, currentNode);
Double rightAvg = gtList.stream().collect(Collectors.averagingInt(new ToIntFunction<Object>() {
@Override
public int applyAsInt(Object value) {
return (int) value;
}
}));
gtList.clear();
updateCurrentNode(currentNode, rightAvg.intValue());
updateNode(root, currentNode.left);
updateNode(root, currentNode.right);
}
public static void updateCurrentNode(Node currentNode, int newVal) {
currentNode.val = newVal;
}
public static void getNodesAverage(Node root, Node node) {
if (node == null || root == null) {
return;
}
if (root.val > node.val) {
gtList.add(root.val);
}
getNodesAverage(root.left, node);
getNodesAverage(root.right, node);
}
}