网页和网站有什么关系,品牌建设意识薄弱,wordpress只能进首页,网站做支付功能文章目录 题目描述思路复杂度Code 题目描述 思路
遍历思想(利用二叉树的中序遍历) 本题的难点在于可能存在多个答案#xff0c;并且要返回最小的那一个#xff0c;为了解决这个问题#xff0c;我门则要利用上二叉搜索树中序遍历为有序序列的特性#xff0c;具体到代码中并且要返回最小的那一个为了解决这个问题我门则要利用上二叉搜索树中序遍历为有序序列的特性具体到代码中结合代码看 1.我们用变量res记录最终的结果同时在中序遍历位置处利用Math.abs(root.val - target) Math.abs(res - target)边遍历边更新res的值注意此处是小于号 2.根据 target 和 root.val 的相对大小决定去左右子树搜索如果 target 比 root 大那么 root 的左子树差值肯定更大直接遍历右子树如果 target 比 root 小那么 root 的右子树差值肯定更大直接遍历左子树 3.同时要注意深刻体会二叉树的中序遍历即是在二叉树中遍历完当前根节点的左子树后再准备遍历右子树的时刻 复杂度
时间复杂度: O ( n ) O(n) O(n);其中 n n n为二叉树的节点个数 空间复杂度: O ( h ) O(h) O(h)其中 h h h为二叉树的高度 Code
class Solution {int res Integer.MAX_VALUE;public int closestValue(TreeNode root, double target) {traverse(root, target);return res;}// Write the if judgment logic in the middle order// so that it can be executed from small to large,// ensuring that the final result is the smallest valueprivate void traverse(TreeNode root, double target) {if (root null) {return;}// Depending on the relative size of target and root.val,// search the left and right subtreesif (root.val target) {// Mid-order position if (Math.abs(root.val - target) Math.abs(res - target)) {res root.val;}// If target is larger than root,// then roots left subtree difference must be larger,// and the right subtree is traversed directlytraverse(root.right, target);} else {// If target is smaller than root,// then roots right subtree difference must be larger,// and the left subtree is traversed directlytraverse(root.left, target);// Mid-order position if (Math.abs(root.val - target) Math.abs(res - target)) {res root.val;}}}
}