LeetCode[5] - Binary Tree Right Side View

自己想了這個(gè)方法,有可能不是特別efficient.
一個(gè)queue放普通的BFS。
一個(gè)queue放level。
同時(shí)維護(hù)一個(gè)parent value;維護(hù)一個(gè)跟著BFS跑的level。
每個(gè)node都有一個(gè)lv。一旦lv和正在跑的level不一樣,證明lv>level,那么也就是說,剛剛換行拉。parent的值,就是上一行最右邊的值。DONE.

/*
Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

For example:
Given the following binary tree,
   1            <---
 /   \\
2     3         <---
 \\     \\
  5     4       <---
You should return [1, 3, 4].

Tags: Tree, Depth-first Search, Breadth-first Search
Similar Problems: (M) Populating Next Right Pointers in Each Node

*/

/*
Thoughts:
Use 2 queue: one for BFS, one for level. Each node in queue has a corresponding level
Track level.
WHen level != levelQ.poll(), that means we are moving to next level, and we should record the previous(parent) node's value.
*/

/**
 * 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> rightSideView(TreeNode root) {
        List<Integer> rst = new ArrayList<Integer>();
        if (root == null) {
            return rst;
        }   
        Queue<TreeNode> q = new LinkedList<TreeNode>();
        Queue<Integer> levelQ = new LinkedList<Integer>();
        q.offer(root);
        levelQ.offer(1);
        int level = 1;
        int parent = root.val;
        TreeNode node = null;
        
        while (!q.isEmpty()) {
            node = q.poll();
            int lv = levelQ.poll();
            if (level != lv) {
                level++;
                rst.add(parent);
            }
            parent = node.val;
            if (node.left != null) {
                q.offer(node.left);
                levelQ.offer(lv + 1);
            } 
            if (node.right != null) {
                q.offer(node.right);
                levelQ.offer(lv + 1);
            }
        }//END while
        rst.add(parent);
        return rst;
    }
}










最后編輯于
?著作權(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的問題, 分享了一些自己做題目的經(jīng)驗(yàn)。 張土汪:刷leetcod...
    土汪閱讀 12,899評(píng)論 0 33
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,533評(píng)論 19 139
  • MediumGiven a binary tree, imagine yourself standing on t...
    greatseniorsde閱讀 156評(píng)論 0 0
  • 導(dǎo)語: 如果你已經(jīng)加入了iOS攻城獅隊(duì)伍,那么我們由衷地祝賀您正式成為一名終身學(xué)習(xí)的程序猿;有人覺得這句話...
    超人猿閱讀 2,546評(píng)論 3 19
  • “婚姻承載不了太多的東西。你想要實(shí)現(xiàn)的人生理想要靠自己,你自己獨(dú)立了,對(duì)方給你的都是驚喜。”
    鄧唄唄l閱讀 253評(píng)論 0 0

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