`

Leetcode - Closest Binary Search Tree Value II

 
阅读更多
Given a non-empty binary search tree and a target value, find k values in the BST that are closest to the target.

Note:
Given target value is a floating point.
You may assume k is always valid, that is: k ≤ total nodes.
You are guaranteed to have only one unique set of k values in the BST that are closest to the target.
Follow up:
Assume that the BST is balanced, could you solve it in less than O(n) runtime (where n = total nodes)?

[分析]
参考https://leetcode.com/discuss/55240/ac-clean-java-solution-using-two-stacks
中序遍历结果是将树中元素从小到大排列,逆式的中序遍历即先遍历右子树再访问根节点最后遍历左子树会得到树中元素从大到小排列的结果,因此可通过中序遍历获取最接近target节点的perdecessors,通过逆中序遍历获取最接近target节点的successors,然后merge perdecessors 和 successors 获取最接近target节点的 k个节点值。
注意到在中序遍历时遇到比target 大的节点即停止,因为由BST的性质可知后面的元素均会比target 大,即所有target的predecessors均已找到,同理逆中序遍历时遇到不大于 target的节点即可停止递归。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<Integer> closestKValues(TreeNode root, double target, int k) {
        List<Integer> result = new ArrayList<Integer>();
        LinkedList<Integer> stackPre = new LinkedList<Integer>();
        LinkedList<Integer> stackSucc = new LinkedList<Integer>();
        inorder(root, target, false, stackPre);
        inorder(root, target, true, stackSucc);
        while (k-- > 0) {
            if (stackPre.isEmpty()) {
                result.add(stackSucc.pop());
            } else if (stackSucc.isEmpty()) {
                result.add(stackPre.pop());
            } else if (Math.abs(stackPre.peek() - target) < Math.abs(stackSucc.peek() - target)) {
                result.add(stackPre.pop());
            } else {
                result.add(stackSucc.pop());
            }
        }
        return result;
    }
    public void inorder(TreeNode root, double target, boolean reverse, LinkedList<Integer> stack) {
        if (root == null) return;
        inorder(reverse ? root.right : root.left, target, reverse, stack);
        if ((reverse && root.val <= target) || (!reverse && root.val > target))
            return;
        stack.push(root.val);
        inorder(reverse ? root.left : root.right, target, reverse, stack);
    }
}
分享到:
评论

相关推荐

    LeetCode最全代码

    * [Binary Search Tree](https://github.com/kamyu104/LeetCode#binary-search-tree) * [Breadth-First Search](https://github.com/kamyu104/LeetCode#breadth-first-search) * [Depth-First Search]...

    lrucacheleetcode-Coding-Interview:编程面试

    lru cache leetcode Coding-Interview A repo for popular coding interview ...Leetcode. ...II Search ...Search ...Closest Binary Search Tree Value 二叉树查找/二叉树第K个 Kth Smallest Element In A

    Python_leetcode.zip

    "closest-binary-search-tree-value-ii.py"是一个涉及二叉搜索树遍历的问题。在二叉搜索树中寻找最近的两个节点,要求改变路径中的一个节点。Python的递归和树遍历策略在这里得到应用,展示了Python在数据结构操作上...

    leetcode分类-leetcode:leetcode

    例如,最近的节点对(Closest Binary Search Tree Value II)考察了对二叉搜索树的理解和操作。 3. **动态规划**:动态规划是一种解决最优化问题的方法,通常涉及状态转移方程。如斐波那契数列(Fibonacci Number)...

    leetcode刷题列表

    例如,树的层级遍历(Levelorder Traversal)、判断树的对称性(Symmetric Tree)、找到二叉搜索树中距离某个值最近的节点(Closest Binary Search Tree Value)等。这些题目通常要求编写者熟悉树的结构和遍历方法,...

    C#-Leetcode编程题解之第16题最接近的三数之和.zip

    在本压缩包中,主题聚焦于使用C#解决LeetCode上的第16题——"最接近的三数之和"(Closest Binary Search Tree Value III)。LeetCode是一个广受欢迎的在线编程挑战平台,旨在帮助程序员提升算法技能和解决实际问题的...

Global site tag (gtag.js) - Google Analytics