問題: Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST.
方法: BST特性是右節點一定大於根節點,左節點一定小於根節點;通過遞迴的方式,先遍歷右子樹,求右子樹所有節點值的和,根節點的值就等於當前值加右子樹的和;同理,遍歷左子樹時,左子樹節點的值等於當前值加上其所有父級節點及父節點右子樹的和。
具體實現:
class ConvertBSTtoGreaterTree {
var sum = 0
class TreeNode(var `val`: Int = 0) {
var left: TreeNode? = null
var right: TreeNode? = null
}
fun convertBST(root: TreeNode?): TreeNode? {
if(root == null) {
return null
}
convertBST(root.right)
root.`val` += sum
sum = root.`val`
convertBST(root.left)
return root
}
companion object {
fun dfs(root: TreeNode?) {
if (root == null) {
return
}
print("${root?.`val`} ")
dfs(root.left)
dfs(root.right)
}
}
}
fun main(args: Array<String>) {
val root = ConvertBSTtoGreaterTree.TreeNode(4)
root.left = ConvertBSTtoGreaterTree.TreeNode(2)
root.right = ConvertBSTtoGreaterTree.TreeNode(8)
(root.left)?.left = ConvertBSTtoGreaterTree.TreeNode(1)
(root.left)?.right = ConvertBSTtoGreaterTree.TreeNode(3)
(root.right)?.right = ConvertBSTtoGreaterTree.TreeNode(9)
val convertBSTtoGreaterTree = ConvertBSTtoGreaterTree()
val result = convertBSTtoGreaterTree.convertBST(root)
ConvertBSTtoGreaterTree.dfs(result)
println()
}
複製程式碼
有問題隨時溝通