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

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

1 /** 2  * Definition for a binary tree node. 3  * public class TreeNode { 4  *     int val; 5  *     TreeNode left; 6  *     TreeNode right; 7  *     TreeNode(int x) { val = x; } 8  * } 9  */10 public class Solution {11     public List
closestKValues(TreeNode root, double target, int k) {12 List
result = new ArrayList<>();13 if (k == 0 || root == null) {14 return result;15 }16 17 Stack
successor = new Stack<>();18 Stack
precessor = new Stack<>();19 20 initialStack(successor, root, true, target);21 initialStack(precessor, root, false, target);22 23 if(!successor.isEmpty() && !precessor.isEmpty() && successor.peek().val == precessor.peek().val) {24 getNext(precessor, false);25 }26 27 while (result.size() < k) {28 if (successor.isEmpty()) {29 result.add(getNext(precessor, false));30 } else if (precessor.isEmpty()) {31 result.add(getNext(successor, true));32 } else {33 boolean sclose = Math.abs((double) successor.peek().val - target) < Math.abs((double)precessor.peek().val - target);34 if (sclose) {35 result.add(getNext(successor, true));36 } else {37 result.add(getNext(precessor, false));38 }39 }40 }41 return result;42 }43 44 private void initialStack(Stack
stack, TreeNode root, boolean successor, double target) {45 while (root != null) {46 if (root.val == target) {47 stack.push(root);48 break;49 } else if (root.val > target == successor) {50 stack.push(root);51 root = successor ? root.left : root.right;52 } else {53 root = successor ? root.right : root.left;54 }55 }56 }57 58 private int getNext(Stack
stack, boolean successor) {59 TreeNode current = stack.pop();60 int result = current.val;61 current = successor ? current.right : current.left;62 while (current != null) {63 stack.push(current);64 current = successor ? current.left : current.right;65 }66 return result;67 }68 }

 

转载于:https://www.cnblogs.com/shuashuashua/p/5723603.html

你可能感兴趣的文章
Python sys模块简介
查看>>
2019-4-23 反射学习笔记
查看>>
Python数据科学手册
查看>>
CSS中hover出现二级菜单
查看>>
前端学PHP之正则表达式函数
查看>>
设计模式(一)观察者模式
查看>>
二叉树遍历入门 Lebal:research
查看>>
迁项目、领任务
查看>>
git
查看>>
IoC深入理解
查看>>
远程部署项目,修改catalina.bat文件 完美解决在代理服务器上HttpURLConnection 调接口超时的问题...
查看>>
HTTP===如何理解网关
查看>>
Spark DataFrame的groupBy vs groupByKey
查看>>
毕业诗
查看>>
PHP7语法知识(一):语言基础
查看>>
luoguP2711 小行星
查看>>
学习android学习必备的java基础知识--四大内部类
查看>>
开源爬虫软件汇总
查看>>
#linux shell#模拟日志生成过程
查看>>
Scroll View 使用心得
查看>>