272. Closest Binary Search Tree Value II

import java.util.*
import kotlin.collections.ArrayList

/**
 * Lock by leetcode
 * 272. Closest Binary Search Tree Value II
 * https://www.lintcode.com/problem/closest-binary-search-tree-value-ii/description
 * https://www.cnblogs.com/grandyang/p/5247398.html
 *
 * 当遍历到一个节点时,如果此时结果数组不到k个,我们直接将此节点值加入结果 res 中,
 * 如果该节点值和目标值的差值的绝对值小于结果 res 的首元素和目标值差值的绝对值,说明当前值更靠近目标值,则将首元素删除,末尾加上当前节点值
 */

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

class Solution {
    fun closestKValues(root_: TreeNode?, target: Double, k: Int): List<Int> {
        //inorder
        val result = ArrayList<Int>(k)
        var root = root_
        val stack = Stack<TreeNode>()
        while (root != null || stack.isNotEmpty()) {
            if (root != null) {
                stack.add(root)
                root = root.left!!
            } else {
                root = stack.pop()
                if (result.size < k) {
                    result.add(root.`val`)
                } else if (Math.abs(target - root.`val`) < Math.abs(target - result.get(0))) {
                    result.remove(0)
                    result.add(root.`val`)
                }
                root = root.right!!
            }
        }
        return result
    }
}
posted @ 2019-12-13 01:36  johnny_zhao  阅读(101)  评论(0编辑  收藏  举报