653. Two Sum IV – Input is a BST

653. Two Sum IV – Input is a BST

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
  public boolean findTarget(TreeNode root, int k) {
		ArrayList data = new ArrayList();
		traverers(root, data);
		for (int i  = 0 ; i < data.size() ; i++)
			for (int j  = 0 ; j < data.size() && i!=j ; j++)
				if (data.get(i) + data.get(j) == k)
					return true;

		return false;
	}

	private void traverers(TreeNode root, ArrayList data) {
		if (root != null) {
			data.add(root.val);
			traverers(root.left, data);
			traverers(root.right, data);
		}
	}
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s