LeetCode之Convert BST to Greater Tree(Kotlin)

問題: 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.git


方法: BST特性是右節點必定大於根節點,左節點必定小於根節點;經過遞歸的方式,先遍歷右子樹,求右子樹全部節點值的和,根節點的值就等於當前值加右子樹的和;同理,遍歷左子樹時,左子樹節點的值等於當前值加上其全部父級節點及父節點右子樹的和。github

具體實現:bash

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()
}
複製代碼

有問題隨時溝通ui

具體代碼實現能夠參考Githubspa

相關文章
相關標籤/搜索