LintCode-900: Closest Binary Search Tree Value

我用的方法就是二分递归。当root->val > target时,结果只可能在root和左子树中选,否则就是在root和右子树中选。
代码如下:

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param root: the given BST
     * @param target: the given target
     * @return: the value in the BST that is closest to the target
    */
    int closestValue(TreeNode * root, double target) {
        if (!root) return INT_MAX;
        double currGap=abs(root->val-target);

        if (target>root->val) {
            if (root->right) {
                int rightCandidate = closestValue(root->right, target);
                double rightGap=abs(rightCandidate - target);
                if (rightGapreturn rightCandidate;
            }
            return root->val;

        } else {
            if (root->left) {
                int leftCandidate = closestValue(root->left, target);
                double leftGap=abs(leftCandidate - target);
                if (leftGapreturn leftCandidate;
            }
            return root->val;
        }
    }
};

另外看到这个链接给出了简明扼要的递归和迭代两种解法,非常好。
http://rainykat.blogspot.com/2017/01/leetcode-270-closest-binary-search-tree.html
递归版:

public class Solution {
    public int closestValue(TreeNode root, double target) {
        // 选出子树的根节点
        TreeNode kid = target < root.val ? root.left : root.right;
        // 如果没有子树,也就是递归到底时,直接返回当前节点值
        if(kid == null) return root.val;
        // 找出子树中最近的那个节点
        int closest = closestValue(kid, target);
        // 返回根节点和子树最近节点中,更近的那个节点
        return Math.abs(root.val - target) < Math.abs(closest - target) ? root.val : closest;
    }
}

迭代版:
We the node is in tree so traveling the BST and keep a value closet to target

Complexity: O(lgN)

public class Solution {
    public int closestValue(TreeNode root, double target) {
        int closest = root.val;
        while(root!=null){
            //if current root.val is closer, update closest 
            closest = Math.abs(closest-target)//do binary search
            root = targetreturn closest;
    }
}

你可能感兴趣的:(LintCode-900: Closest Binary Search Tree Value)