50
/ \
/ \
8 2
/ \ /\
/ \ / \
3 5 1 30
package tree;
public class ConvertSumP {
/**
* 将任意一颗二叉树转变为每一个节点都是另外两个孩子节点的和,要求
* 只能增加某一个节点的值,节点为null视为0
* @param args
*/
public static void convert(TreeNode root){
if(root==null||(root.left==null&&root.right==null)) return;
convert(root.left);
convert(root.right);
int left = getsum(root.left);
int right = getsum(root.right);
if(root.value==left+right){
return;
}else if(root.value<left+right){
root.value = left+right;
}else{
if(root.left!=null){
root.left.value+=root.value-left-right;
convert(root.left);
}else{
root.right.value += root.value-left-right;
convert(root.right);
}
}
}
private static int getsum(TreeNode root) {
if(root==null) return 0;
return root.value;
}
public static void print(TreeNode root){
if(root==null) return;
System.out.print(root.value+" ");
print(root.left);
print(root.right);
}
public static void main(String[] args) {
TreeNode root = new TreeNode(50);
root.left = new TreeNode(7);
root.right = new TreeNode(2);
root.left.left = new TreeNode(3);
root.left.right = new TreeNode(5);
//root.right.left = new TreeNode(1);
root.right.right = new TreeNode(30);
print(root);
convert(root);
System.out.println();
print(root);
}
}
50 / \ / \ 19 31 / \ / \ / \ / \14 5 1 30