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;
}
}
/**
* 3
* 2 5
* 1 4 6
*
* 转换成
* 5
* 4 6
* 5 5 0
*/
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;
}
// 选取大于当前节点的nodes
getNodesAverage(root, currentNode);
Double rightAvg = gtList.stream().collect(Collectors.averagingInt(new ToIntFunction<Object>() {
@Override
public int applyAsInt(Object value) {
return (int) value;
}
}));
gtList.clear();
// updateNodeValue
updateCurrentNode(currentNode, rightAvg.intValue());
// 递归节点
updateNode(root, currentNode.left);
updateNode(root, currentNode.right);
}
/**
* 重置节点value
*/
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);
}
}
版权声明:本文为luman1991原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。