您的位置:首页 > 其它

将任意一颗二叉树转变为每一个节点都是另外两个孩子节点的和

2014-06-30 16:21 381 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐