C# - iterative - store intermediate best diff value


  • 0
        public int ClosestValue(TreeNode root, double target) 
        {
            if (root == null) return 0;
            
            int val = root.val;
            double bestDiff = Math.Abs(target - val);
            TreeNode node = root;
            while (node != null)
            {
                double diff = Math.Abs(target - node.val);
                if (diff <= bestDiff)
                {
                    bestDiff = diff;
                    val = node.val;
                }
                node = target <= node.val ? node.left : node.right;
            }
            
            return val;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.