Simple C# O(N) time O(N) Space


  • 0
    Y

    List<int> inorder = new List<int>();
    public int ClosestValue(TreeNode root, double target)
    {
    this.Inorder(root);
    double currentDifference = Math.Abs(target-inorder[0]);
    int index = 0;
    for(int i =1;i< inorder.Count;i++)
    {

            if(currentDifference > Math.Abs(target - inorder[i]))
            {
                currentDifference = Math.Abs(target - inorder[i]);
                index = i;
            }
        }
        
        return inorder[index];
    }
    
    public void Inorder(TreeNode root)
    {
        if(root == null) return;
        Inorder(root.left);
        this.inorder.Add(root.val);
        Inorder(root.right);
    }

Log in to reply
 

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