[snap]two sum on tree

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問(wèn)題, 分享了一些自己做題目的經(jīng)驗(yàn)。 張土汪:刷leetcod...
    土汪閱讀 12,923評(píng)論 0 33
  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 11,143評(píng)論 0 23
  • 曉來(lái)清風(fēng)殘?jiān)码x,對(duì)鏡獨(dú)梳妝 。今非昔比來(lái)日茫,玄鬢生白霜。 一夜珠淚草色新,陌上熏花香。山峰壓船星河廣,無(wú)窮無(wú)盡流...
    翦夢(mèng)閱讀 415評(píng)論 40 37
  • 沒(méi)錯(cuò),我觀劇小能手絕非浪得虛名,今天我又回來(lái)啦。 最近在各大社交媒體上被黑得最慘的無(wú)非兩個(gè)劇——《遇見愛(ài)情的利先生...
    吹呀吹泡泡閱讀 1,110評(píng)論 0 51
  • 又是一場(chǎng)深夜! 在被灼熱的空氣包裹的某個(gè)日子里,耳邊忽然驚現(xiàn)了蟬鳴,聒噪之后又驟然收緊,但依然讓我對(duì)這個(gè)夏日的接受...
    儀軒閱讀 312評(píng)論 0 1

友情鏈接更多精彩內(nèi)容