Leetcode - Closest Binary Search Tree Value

My code:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    private int pre = Integer.MIN_VALUE;
    public int closestValue(TreeNode root, double target) {
        Stack<TreeNode> st = new Stack<TreeNode>();
        TreeNode p = root;
        while (p != null) {
            st.push(p);
            p = p.left;
        }
        
        while (!st.isEmpty()) {
            TreeNode curr = st.pop();
            if (pre == Integer.MIN_VALUE) {
                if (target <= curr.val) {
                    return curr.val;
                }
                else {
                    pre = curr.val;
                }
            }
            else {
                if (target <= curr.val) {
                    double diff = Math.abs((double) pre - target) - Math.abs((double) curr.val - target);
                    if (diff > 0) {
                        return curr.val;
                    }
                    else {
                        return pre;
                    }
                }
                else {
                    pre = curr.val;
                }
            }
            
            if (curr.right != null) {
                curr = curr.right;
                while (curr != null) {
                    st.push(curr);
                    curr = curr.left;
                }
            }
        }
        
        return pre;
    }
}

不知道为什么,我第一个想到的会是 inorder 遍历来找这个值。。。
感觉好蠢,时间复杂度是 O(n), 空间复杂度是O(n) !!!

然后看了答案,为什么会想不到拿binary search 来找呢??

My code:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int closestValue(TreeNode root, double target) {
        int ret = root.val;
        while (root != null) {
            if (Math.abs(root.val - target) < Math.abs(ret - target)) {
                ret = root.val;
            }
            if (root.val > target) {
                root = root.left;
            }
            else {
                root = root.right;
            }
        }
        
        return ret;
    }
}

reference:
https://discuss.leetcode.com/topic/25219/clean-and-concise-java-solution

时间复杂度: O(log n)
空间复杂度: O(1)

我太蠢了。。。

Anyway, Good luck, Richardo! – 09/07/2016

    原文作者:Richardo92
    原文地址: https://www.jianshu.com/p/091def47ced9#comments
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞