• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Leetcode: Binary Tree Right Side View

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].

这道题就是BT的Level Order Traversal,每次要换一层的时候,记录当前节点

 1 /**
 2  * Definition for binary tree
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public List<Integer> rightSideView(TreeNode root) {
12         ArrayList<Integer> res = new ArrayList<Integer>();
13         if (root == null) return res;
14         LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
15         queue.offer(root);
16         int PNum = 1;
17         int CNum = 0;
18         while (!queue.isEmpty()) {
19             TreeNode cur = queue.poll();
20             PNum--;
21             if (cur.left != null) {
22                 queue.offer(cur.left);
23                 CNum++;
24             }
25             if (cur.right != null) {
26                 queue.offer(cur.right);
27                 CNum++;
28             }
29             if (PNum == 0) {
30                 res.add(cur.val);
31                 PNum = CNum;
32                 CNum = 0;
33             }
34         }
35         return res;
36     }
37 }

 注意,每次都是先添加右边child,所以是i==0的时候add

 1 public class Solution {
 2     public List<Integer> rightSideView(TreeNode root) {
 3         // reverse level traversal
 4         List<Integer> result = new ArrayList();
 5         Queue<TreeNode> queue = new LinkedList();
 6         if (root == null) return result;
 7 
 8         queue.offer(root);
 9         while (queue.size() != 0) {
10             int size = queue.size();
11             for (int i=0; i<size; i++) {
12                 TreeNode cur = queue.poll();
13                 if (i == 0) result.add(cur.val);
14                 if (cur.right != null) queue.offer(cur.right);
15                 if (cur.left != null) queue.offer(cur.left);
16             }
17 
18         }
19         return result;
20     }
21 }

 

posted @ 2015-04-11 07:06  neverlandly  阅读(789)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3