博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode-Closest Binary Search Tree Value II
阅读量:5077 次
发布时间:2019-06-12

本文共 1580 字,大约阅读时间需要 5 分钟。

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)?

Analysis:

Use inorder traverse, put all predecessors into a stack, for every successor, put all pres that has smaller gap than that successor into resList and then put this successor into resList.

Solution:

/** * 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
closestKValues(TreeNode root, double target, int k) { Stack
pres = new Stack
(); LinkedList
resList = new LinkedList
(); closestKValuesRecur(root,target,k,pres,resList); // If not enough in resList, put more pres into resList. This is because successor is too little. while (resList.size()
pres, LinkedList
resList){ if (curNode == null) return; if (resList.size()==k) return; // inorder traverse. closestKValuesRecur(curNode.left,target,k,pres,resList); // check curNode if (curNode.val >= target){ while (resList.size()

 

转载于:https://www.cnblogs.com/lishiblog/p/5836167.html

你可能感兴趣的文章
mac lion 系统安装
查看>>
Linux下程序守护脚本的应用实例
查看>>
win7开启Administrator账户
查看>>
Vue.js中全局组件和局部组件的编写差异和注意事项
查看>>
cordova 日曆 聯系人 插件使用
查看>>
1046: [HAOI2007]上升序列(dp)
查看>>
Maven创建Web项目、、、整合SSM框架
查看>>
转!!深入理解 Session 与 Cookie
查看>>
Dojo 1.6 beta1 发布
查看>>
用node.js做cluster,监听异常的邮件提醒服务
查看>>
Ninject 2.x细说---1.基本使用
查看>>
css,js加载阻塞页面渲染的理解
查看>>
合并相同字段
查看>>
黑名单设计
查看>>
TP5 查询mysql数据库时的find_in_set用法
查看>>
ATL添加事件步骤
查看>>
Avoid memory copying between user space and kernel space
查看>>
隐藏input输入框的增减按钮
查看>>
Python 常用模块总结
查看>>
谷歌地图使用
查看>>