two node sum to a target on a binary search tree.
I think there should be a better solution...
The below code, I didn't check it, but I think it is correct...
package snapchat;
import java.util.HashSet;
import java.util.Set;
import java.util.Stack;
/**
* Created by kangyue on 1/8/17.
*/
class TreeNode{
TreeNode left;
TreeNode right;
int val;
TreeNode(){
this.val = val;
}
}
public class TwoSumTree {
public boolean sumToTarget(TreeNode root, int target){
Set<Integer> set = new HashSet<>();
Stack<TreeNode> st = new Stack<>();
TreeNode cur = root;
while(!st.isEmpty() || cur != null){
while(cur != null){
st.push(cur);
cur = cur.left;
}
cur = st.pop();
if(set.contains(target - cur.val))return true;
set.add(cur.val);
cur = cur.right;
}
return false;
}
}
网友评论