`

Transform a Binary Search Tree into a Greater Sum Tree

 
阅读更多

Given a Binary Search Tree (where all nodes on the left child branch are less than the node), and all nodes to the right are greater/equal to the node), transform it into a Greater Sum Tree where each node contains sum of it together with all nodes greater than that node. Example diagram is here:

enter image description here

int sum = 0;
public TreeNode replaceBST(TreeNode node) {
	if(node == null) return null;
	replaceBST(node.right);
	int tmp = node.val;
	node.val = sum;
	sum += tmp;
	replaceBST(node.left);
	return node;
}

 

如果最大的节点的值不被更新为0的话,可以这样:

int sum = 0;
boolean changed = false;
public TreeNode replaceBST(TreeNode node) {
	if(node == null) return null;
	replaceBST(node.right);
	int tmp = node.val;
	if(changed) {
		node.val = sum;
		sum += tmp;
	} else {
		changed = true;
		sum = node.val;
	}
	replaceBST(node.left);
	return node;
}

Reference:

http://codereview.stackexchange.com/questions/55966/transform-a-binary-search-tree-into-a-greater-sum-tree?rq=1

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics