O(N) inorder short solution


  • 0
    T

    public class Solution {

    public IList<int> ClosestKValues(TreeNode root, double target, int k) {
        IList<int> result = new List<int>();
        dfs(root,target,k,result);
         return result;
    }
    
    private void dfs(TreeNode root,double target,int k,IList<int> result){
        if(root == null)
            return;
            
        dfs(root.left,target,k,result);
        
        if(result.Count < k)
            result.Add(root.val);
        else if(Math.Abs(root.val-target) >= Math.Abs(result[k-1]-target) && Math.Abs(root.val-target) >= Math.Abs(result[0]-target))
            return;
        else{
            result.RemoveAt(0);
            result.Add(root.val);
        }
        
        dfs(root.right,target,k,result);
        
    }
    

    }


Log in to reply
 

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