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

相关文章
相关标签/搜索