Tree BFS - LC314 Binary Tree Vertical Order Traversal

題目:
Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bottom, column by column).If two nodes are in the same row and column, the order should be from left to right.

這道題的目的是把樹(shù)按列輸出,以root為其實(shí)點(diǎn)按層遍歷,節(jié)點(diǎn)的左邊列標(biāo)-1,節(jié)點(diǎn)的右邊列標(biāo)+1。然后為了找到起始點(diǎn)好遍歷map的keyset,我們用 left_margin 來(lái)記錄起始位置。

   public  List<List<Integer>> verticalOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        Map<Integer, List<Integer>> map = new HashMap();
        int left_margin = 0; 
        Queue<TreeNodePlus> queue = new LinkedList();
        if(root != null) addToQueue(queue, root, 0);
        for(TreeNodePlus nodeplus = queue.poll(); nodeplus != null; nodeplus = queue.poll()){
            List<Integer> list =  map.get(nodeplus.colomn);
            if(list == null){
                list = new ArrayList();
                list.add(nodeplus.node.val);
                map.put(nodeplus.colomn, list);
            } else list.add(nodeplus.node.val);
            
            if(nodeplus.node.left != null){
                int temp = nodeplus.colomn - 1;
                left_margin = Integer.min(left_margin, temp);
                addToQueue(queue, nodeplus.node.left, temp);
            }
            
            if(nodeplus.node.right != null) addToQueue(queue, nodeplus.node.right, nodeplus.colomn + 1);
        }
        if(!map.isEmpty()) for(int i = 0; i < map.size() ; ++i) res.add(map.get(i + left_margin));
        return res;
    }
    
    public void addToQueue(Queue<TreeNodePlus> queue, TreeNode node, int colomn){
        TreeNodePlus plus = new TreeNodePlus(node, colomn);
        queue.offer(plus);
    }
    
    public class TreeNodePlus {
        TreeNode node;
        int colomn;
        public TreeNodePlus(TreeNode node, int colomn){
            this.node = node;
            this.colomn = colomn;
        }
    }
?著作權(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)書(shū)系信息發(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
  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,590評(píng)論 19 139
  • 94. Binary Tree Inorder Traversal 中序 inorder:左節(jié)點(diǎn)->根節(jié)點(diǎn)->右節(jié)...
    Morphiaaa閱讀 764評(píng)論 0 0
  • 1〗 “她是個(gè)‘不正常的孩子’?!?提到她的時(shí)候媽媽這么說(shuō),叮囑小侄子不要去靠近她,不要和她在一起玩耍,不要把零食...
    如煙魚(yú)閱讀 515評(píng)論 2 2
  • 第一次來(lái)麗江。 第一次一個(gè)人,獨(dú)自。 下了飛機(jī),云淡風(fēng)輕。我坐在機(jī)場(chǎng)大巴上,徐徐前行。其實(shí)我是來(lái)短期支教的。 車載...
    睫毛彎彎ww閱讀 632評(píng)論 0 0

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