美文网首页
[snap]two sum on tree

[snap]two sum on tree

作者: 秋_轩 | 来源:发表于2017-01-08 14:31 被阅读0次

two node sum to a target on a binary search tree.

instant

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;
        
    }
}

相关文章

网友评论

      本文标题:[snap]two sum on tree

      本文链接:https://www.haomeiwen.com/subject/swbqbttx.html