ALGO:
爲了遍歷做反向,並更新總和
這裏是java實現
public static void modifyWithSumOfGreaterNodes(BinaryTreeNode<Integer> bst) {
doModifyWithSumOfGreaterNodes(bst, new MutableInteger(0));
}
private static void doModifyWithSumOfGreaterNodes(BinaryTreeNode<Integer> bst, MutableInteger sum) {
if (bst == null) {
return ;
}
doModifyWithSumOfGreaterNodes(bst.getRight(), sum);
sum.add(bst.getData());
bst.setData(sum.getValue());
doModifyWithSumOfGreaterNodes(bst.getLeft(), sum);
}
這裏是單元測試
@Test
public void replaceBSTNodesWithSumOfNodesGreaterOrEqualToNodeTest() {
BinaryTreeNode<Integer> eighty = new BinaryTreeNode<Integer>(80);
BinaryTreeNode<Integer> sixty = new BinaryTreeNode<Integer>(60);
BinaryTreeNode<Integer> forty = new BinaryTreeNode<Integer>(40);
BinaryTreeNode<Integer> twenty = new BinaryTreeNode<Integer>(20);
BinaryTreeNode<Integer> seventy = new BinaryTreeNode<Integer>(70, sixty, eighty);
BinaryTreeNode<Integer> thrity = new BinaryTreeNode<Integer>(30, twenty, forty);
BinaryTreeNode<Integer> root = new BinaryTreeNode<Integer>(50, thrity, seventy);
BinaryTreeUtil.modifyWithSumOfGreaterNodes(root);
assertThat(BinaryTreeUtil.iPostOrder(root).toArray(new Integer[0]), equalTo(new Integer[]{350,300,330,210,80,150,260}));
}
5 5 5不是bst,檢查[bs (http://www.geeksforgeeks.org/a-program-to-check-if-a-binary-tree-is-bst-or-not/) – craftsmannadeem 2016-04-11 16:29:13
(允許重複鍵的搜索樹_should_允許他們到一個固定的一邊,只有 - 左右相等的密鑰纔是不可能的。) – greybeard 2016-10-08 19:28:26