[leetcode#270] Closest Binary Search Tree Value

Source: Internet
Author: User

problem:

Given a non-empty binary search tree and a target value, find the value in the BST that's closest to the target.

Note:

    • Given target value is a floating point.
    • Guaranteed to has only one unique value in the BST, which is closest to the target.

Wrong solution 1:

 Public classSolution { Public intClosestvalue (TreeNode root,Doubletarget) {        if(Root = =NULL)            Throw NewIllegalArgumentException ("Root is null"); intClosest_gap =Integer.max_value; intret;  while(Root! =NULL) {            if(Math.Abs (Target-root.val) <closest_gap) {Closest_gap= Math.Abs (Target-root.val); RET=Root.val; }            if(target = =root.val)returnRoot.val; Else if(Target <root.val) Root=Root.left; ElseRoot=Root.right; }        returnret; }}

MistakesAnalysis:

Line 18:error:incompatible types:possible lossy conversion fromDoubleToint Line55: error:variable ret might not has been initializedmistake1: Even the problem has emphasized-a, a floating type, the Val in node is Integer type. I still blindly ignore the fact that:the type used forRecording the distance should be afloattype rather than Integer. Otherwise, we could lose precision. Case:target= 0.3Val_1:-1, Val_2:1(int) (Target-val_1) = 1;(int) (target-val_2) = 1; Wrong Fix:DoubleClosest_gap =Integer.max_value, .....if(Target-(Math.Abs) (Double) Root.val) <closest_gap) {Closest_gap= Math.Abs (Target-(Double) root.val); RET=Root.val;} ... Mistake2: Since"RET" is areturnValue, and it is solely enclosed inif-ElseBlocks, we must initialize it.

Wrong Solution 2:

 Public classSolution { Public intClosestvalue (TreeNode root,Doubletarget) {        if(Root = =NULL)            Throw NewIllegalArgumentException ("Root is null"); DoubleClosest_gap =Integer.max_value; intRET = 0;  while(Root! =NULL) {            if(Target-(Math.Abs) (Double) root.val) <=closest_gap) {Closest_gap= Math.Abs (Target-(Double) root.val); RET=Root.val; }            if(target = =root.val)returnRoot.val; Else if(Target <root.val) Root=Root.left; ElseRoot=Root.right; }        returnret; }}

MistakesAnalysis:

Error cases:[1500000000,1400000000], -1500000000.0Output:0expected:1400000000   Double, I still fail to consider the A floating point "target" could has larger range than Integer, WH Ich would produce the distance larger than "Integer.max_value". double closest_gap = integer.max_value; Fix:double closest_gap = Double.max_value;

Skill:

Finally, we get it right!!! But ThisA good lesson forus to learn a important skill:avoiding overflow through the advanced primitive types. Actually, we have meet it many times:reverse Integer, convert String into integer.we know:whether"Add" or "minus", we could easily exceed the operand ' s value range.Take the Integer as Example:integer. Max_value+ 1Overflow;integer. Min_value-1overflow; Even the operation between Integer with Double could easily result in overflow problem. Double.max_value+ 1overflow;double. Min_value-1overflow. Thus We have the take advantage of the advanced type!!!for the operations among Integer, we useLongTo hold the result.Longres = integer1 + integer 2. for ThisProblem, we were guaranteed, the target is a single floating point, it means we can use "double" to handle the result. <or forThe maximum comparision>note:closestvalue (TreeNode root,DoubleTarget) is a little misleading, but it's indeed a single floating point.

Solution:

 Public classSolution { Public intClosestvalue (TreeNode root,Doubletarget) {        if(Root = =NULL)            Throw NewIllegalArgumentException ("Root is null"); DoubleClosest_gap =Double.max_value; intRET = 0;  while(Root! =NULL) {            if(Target-(Math.Abs) (Double) root.val) <=closest_gap) {Closest_gap= Math.Abs (Target-(Double) root.val); RET=Root.val; }            if(target = =root.val)returnRoot.val; Else if(Target <root.val) Root=Root.left; ElseRoot=Root.right; }        returnret; }}

[leetcode#270] Closest Binary Search Tree Value

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.