LeetCode[5] - Binary Tree Right Side View

自己想了这个方法,有可能不是特别efficient.
一个queue放普通的BFS。
一个queue放level。
同时维护一个parent value;维护一个跟着BFS跑的level。
每个node都有一个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;
    }
}










最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,768评论 0 33
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,868评论 18 139
  • MediumGiven a binary tree, imagine yourself standing on t...
    greatseniorsde阅读 133评论 0 0
  • 导语: 如果你已经加入了iOS攻城狮队伍,那么我们由衷地祝贺您正式成为一名终身学习的程序猿;有人觉得这句话...
    超人猿阅读 2,332评论 3 19
  • “婚姻承载不了太多的东西。你想要实现的人生理想要靠自己,你自己独立了,对方给你的都是惊喜。”
    邓呗呗l阅读 230评论 0 0