转自: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);
}
}