Easy Java solution.O(n) time and O(n) space.


  • 0
    H

    Easy Java solution.O(n) time and O(n) space.

    public class Solution {
        public boolean findTarget(TreeNode root, int k) {
        List<Integer> list = new LinkedList<>();
            helper(root,list);
            int begin = 0;
            int end = list.size()-1;
    
            while(begin < end){
            	int temp = list.get(begin) + list.get(end);
            	if(temp == k) return true;
            	else if(temp < k) begin++;
            	else end--;
            }
            return false;
            
        }
    
    
        public void helper(TreeNode root, List<Integer> list){
        	if(root == null) return;
    
        	helper(root.left,list);
        	list.add(root.val);
        	helper(root.right,list);
        }
    }
    
    

Log in to reply
 

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