How to get the complexity?


  • 0
    J

    Here is my solution, what is the time and space complexity?

    public class Solution {
        public boolean findTarget(TreeNode root, int k) {
            if(root == null){
                return false;
            }
            Queue<TreeNode> queue = new LinkedList<>();
            queue.offer(root);
            while(!queue.isEmpty()){
                int size = queue.size();
                while(size-- != 0){
                    TreeNode temp = queue.poll();
                    if(temp == null){
                        continue;
                    }
                    queue.offer(temp.left);
                    queue.offer(temp.right);
                    if(temp.val * 2 == k){
                        continue;
                    }
                    if(helper(root, k - temp.val)){
                        return true;
                    }
                }
            }
            return false;
        }
        
        private boolean helper(TreeNode root, int num){
            if(root == null){
                return false;
            }
            if(root.val == num){
                return true;
            }else if(root.val > num){
                return helper(root.left, num);
            }else{
                return helper(root.right, num);
            }
        }
    }
    

Log in to reply
 

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