272. Closest Binary Search Tree Value II

Given a non-empty binary search tree and a target value, find k values in the BST that are closest to the target.

Note:
Given target value is a floating point.
You may assume k is always valid, that is: k ≤ total nodes.
You are guaranteed to have only one unique set of k values in the BST that are closest to the target.
Follow up:
Assume that the BST is balanced, could you solve it in less than O(n) runtime (where n = total nodes)?

一刷
題解:
我們用兩個(gè)棧磨镶,全部采用inorder訪問樹溃蔫。
一個(gè)棧從小到大,存儲(chǔ)<= target的節(jié)點(diǎn)
一個(gè)棧由大到小琳猫,存儲(chǔ)>target的節(jié)點(diǎn)伟叛。
然后比較兩個(gè)棧頭的值,存儲(chǔ)距離較小的點(diǎn)脐嫂,一直進(jìn)行k次统刮。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<Integer> closestKValues(TreeNode root, double target, int k) {
        List<Integer> res = new ArrayList<>();
        
        Stack<Integer> s1 = new Stack<>();//predecessors
        Stack<Integer> s2 = new Stack<>();//successors
        if(root == null) return res;
        
        inorder(root, target, false, s1);//ascending, and store the node with value lower than or equal to target
        inorder(root, target, true, s2);//descending
        while(k-->0){
            if(s1.isEmpty()) res.add(s2.pop());
            else if(s2.isEmpty()) res.add(s1.pop());
            else if(Math.abs(s1.peek() - target)<Math.abs(s2.peek() - target))
                res.add(s1.pop());
            else res.add(s2.pop());
        }
        return res;
    }
    
    private void inorder(TreeNode root, double target, boolean reverse, Stack<Integer> stack){
        if(root == null) return;
        inorder(reverse? root.right:root.left, target, reverse, stack);
        // early terminate, no need to traverse the whole tree
        if((reverse && root.val<=target) || (!reverse && root.val>target)) return;
        // track the value of current node
        stack.push(root.val);
        inorder(reverse? root.left : root.right, target, reverse, stack);
    }
}

二刷
題解:思路同上。但是我們這次用兩個(gè)array和index來模擬上述行為账千。
inorder traverse,
如果root.val小于target, append在smaller尾部
否則侥蒙,append在bigger尾部
所以smaller尾部和bigger的頭部更滿足要求。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<Integer> closestKValues(TreeNode root, double target, int k) {
        List<Integer> smaller = new ArrayList<>();
        List<Integer> bigger = new ArrayList<>();
        //inorder
        inorder(root, target, smaller, bigger);
        int sIndex = smaller.size()-1;
        int bIndex = 0;
        List<Integer> res = new ArrayList<>(k);
        int index = 0;
        while(res.size()<k){
            if(sIndex<0){
                res.add(bigger.get(bIndex++));
            }else if(bIndex == bigger.size()){
                res.add(smaller.get(sIndex--));
            }else{
                if(Math.abs(smaller.get(sIndex) - target) < Math.abs(bigger.get(bIndex) - target)){
                    res.add(smaller.get(sIndex--));
                }else res.add(bigger.get(bIndex++));
            }
        }
        return res;
    }
    
    private void inorder(TreeNode root, double target, List<Integer> smaller, List<Integer> bigger){
        if(root == null) return;
        inorder(root.left, target, smaller, bigger);
        if(root.val<target) smaller.add(root.val);
        else bigger.add(root.val);
        inorder(root.right, target, smaller, bigger);
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末蕊爵,一起剝皮案震驚了整個(gè)濱河市辉哥,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖醋旦,帶你破解...
    沈念sama閱讀 221,430評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件恒水,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡饲齐,警方通過查閱死者的電腦和手機(jī)钉凌,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,406評(píng)論 3 398
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來捂人,“玉大人御雕,你說我怎么就攤上這事±拇睿” “怎么了酸纲?”我有些...
    開封第一講書人閱讀 167,834評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)瑟匆。 經(jīng)常有香客問我闽坡,道長(zhǎng),這世上最難降的妖魔是什么愁溜? 我笑而不...
    開封第一講書人閱讀 59,543評(píng)論 1 296
  • 正文 為了忘掉前任疾嗅,我火速辦了婚禮,結(jié)果婚禮上冕象,老公的妹妹穿的比我還像新娘代承。我一直安慰自己,他們只是感情好渐扮,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,547評(píng)論 6 397
  • 文/花漫 我一把揭開白布论悴。 她就那樣靜靜地躺著,像睡著了一般席爽。 火紅的嫁衣襯著肌膚如雪意荤。 梳的紋絲不亂的頭發(fā)上啊片,一...
    開封第一講書人閱讀 52,196評(píng)論 1 308
  • 那天只锻,我揣著相機(jī)與錄音,去河邊找鬼紫谷。 笑死齐饮,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的笤昨。 我是一名探鬼主播祖驱,決...
    沈念sama閱讀 40,776評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼瞒窒!你這毒婦竟也來了捺僻?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,671評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎匕坯,沒想到半個(gè)月后束昵,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,221評(píng)論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡葛峻,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,303評(píng)論 3 340
  • 正文 我和宋清朗相戀三年锹雏,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片术奖。...
    茶點(diǎn)故事閱讀 40,444評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡礁遵,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出采记,到底是詐尸還是另有隱情佣耐,我是刑警寧澤,帶...
    沈念sama閱讀 36,134評(píng)論 5 350
  • 正文 年R本政府宣布唧龄,位于F島的核電站晰赞,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏选侨。R本人自食惡果不足惜掖鱼,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,810評(píng)論 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望援制。 院中可真熱鬧戏挡,春花似錦、人聲如沸晨仑。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,285評(píng)論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽洪己。三九已至妥凳,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間答捕,已是汗流浹背逝钥。 一陣腳步聲響...
    開封第一講書人閱讀 33,399評(píng)論 1 272
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留拱镐,地道東北人艘款。 一個(gè)月前我還...
    沈念sama閱讀 48,837評(píng)論 3 376
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像沃琅,于是被迫代替她去往敵國(guó)和親哗咆。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,455評(píng)論 2 359

推薦閱讀更多精彩內(nèi)容

  • Given a non-empty binary search tree and a target value, ...
    matrxyz閱讀 328評(píng)論 0 0
  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗(yàn)益眉。 張土汪:刷leetcod...
    土汪閱讀 12,747評(píng)論 0 33
  • 博瑞智趙亮 首先晌柬,現(xiàn)在是大環(huán)境使然姥份,不讓孩子接觸手機(jī),斷絕網(wǎng)絡(luò)年碘,幾乎是不可能的殿衰。我們家長(zhǎng)要緊跟潮流,順應(yīng)孩子心理盛泡。...
    玲03閱讀 142評(píng)論 1 1
  • 你怯懦地祈助的 別人的著作救不了你 你不是別人闷祥, 此刻你正身處 自己的腳步編織起的迷宮的中心之地 ...
    阿清閱讀 434評(píng)論 0 2
  • /#幸福是需要修出來的~每天進(jìn)步1%~幸福實(shí)修09班~21~鄒迪 20170819(33/30)09班 【幸福三朵...
    貓媽Kubaoer閱讀 206評(píng)論 1 0