LeetCode之Binary Search Tree to Greater Sum Tree(Kotlin)

問題: git


方法: 經過DFS遞歸遍歷,中序遍歷;對先遍歷的節點進行求和,全部節點的值都等於原有值加已求和值,最後輸出根節點即爲最終結果。github

具體實現:bash

class BinarySearchTreeToGreaterSumTree {
    class TreeNode(var `val`: Int) {
        var left: TreeNode? = null
        var right: TreeNode? = null
    }

    private var gst = 0

    fun bstToGst(root: TreeNode?): TreeNode? {
        gst = 0
        dfs(root)
        return root
    }

    private fun dfs(root: TreeNode?) {
        if (root == null) {
            return
        }
        dfs(root.right)
        root.`val` += gst
        gst = root.`val`
        dfs(root.left)
    }
}
複製代碼

有問題隨時溝通ui

具體代碼實現能夠參考Githubspa

相關文章
相關標籤/搜索