给定BST,使用大于等于当前节点的总和代替当前节点

转自:http://www.careercup.com/question?id=5679059790987264

Question:

For a given binary search tree, replace each node with sum of all node which are greater then of equal to current node.

对于给定的二叉搜索树,所有的节点都大于等于当前节点的总和取代每个节点。

Answer:

使用中序遍历二叉搜索树,先左右后的顺序,得到的是从小到大的排序。

那么先右后左的顺序得到的就是从大到小的排序。

根据题意,需要将每个节点代替成大于等与当前节点的总和。

那么正好是将元素从最大开始,依次加之前的元素,也正好使用先右后左的中序遍历方法,每次增加之前元素的值,并替换当前节点。

public class BST {

	int data;
	private BST lc;
	private BST rc;
	int sumSoFar;
	BST replaceRootWithSumofGreaterNode(BST root){
		
		if(root != null){
			root.rc = replaceRootWithSumofGreaterNode(root.rc);
			sumSoFar+= root.data;
			root.data = sumSoFar;
			root.lc = replaceRootWithSumofGreaterNode(root.lc);
		}	
		return root;
	}
	BST addNode(BST root, int data){
		
		if(root == null){
			root = new BST();
			root.data = data;
			root.lc = root.rc = null;
			return root;
		}else{
			if(data<root.data){
				root.lc = addNode(root.lc,data);
				return root;
			}
			else{
				root.rc = addNode(root.rc,data);
				return root;
			}
		}
	}
	 void inorder(BST root){
		 if(root!=null){
			 inorder(root.lc);
			 System.out.print(root.data+"->");
			 inorder(root.rc);
		 }
	 }
	public static void main(String[] args) {
		BST b = new BST();
		BST root = null;
		int arr[] = {5,3,8,6,10,1,4,7,9,2};
		for(int data: arr){
			root = b.addNode(root, data);
		}
		b.inorder(root);
		System.out.print("\n\n");
		b.sumSoFar = 0;
		root= b.replaceRootWithSumofGreaterNode(root);
		b.inorder(root);
	}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值