[LeetCode]Binary Tree Right Side View
2015-04-06 17:36
267 查看
原题链接:https://leetcode.com/problems/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,
You should return
题解:
这道题非常有趣,是找二叉树从右侧看的时候能看到的数,其实思路也是很简单,即返回每一层的最右边的一个数就好了,在二叉树的层序遍历的代码上稍作修改即可。对二叉树的层序遍历不太清楚的朋友,可看我之前的博客《二叉树完全总结》。具体没什么好说的,直接上代码:
题意描述:
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].
题解:
这道题非常有趣,是找二叉树从右侧看的时候能看到的数,其实思路也是很简单,即返回每一层的最右边的一个数就好了,在二叉树的层序遍历的代码上稍作修改即可。对二叉树的层序遍历不太清楚的朋友,可看我之前的博客《二叉树完全总结》。具体没什么好说的,直接上代码:
/** * Definition for binary tree * 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> res = new ArrayList<Integer>(); if(root==null) return res; Queue<TreeNode> Q = new LinkedList<TreeNode>(); Q.offer(root); int curLevel = 1; res.add(root.val); while(!Q.isEmpty()){ int levelSize = Q.size(); int count = 0; TreeNode last = null; while(count<levelSize){ TreeNode p = Q.poll(); if(p.left!=null){ last = p.left; Q.offer(p.left); } if(p.right!=null){ last = p.right; Q.offer(p.right); } count++; } if(last!=null) res.add(last.val); } return res; } }
相关文章推荐
- 199 Binary Tree Right Side View-LeetCode
- [LeetCode] Binary Tree Right Side View 二叉树的右侧视图
- leetcode 日经贴,Cpp code -Binary Tree Right Side View
- LeetCode "Binary Tree Right Side View"
- Leetcode Binary Tree Right Side View
- leetCode 101/199-Symmetric Tree/Binary Tree Right Side View
- 【LeetCode】Binary Tree Right Side View 解题报告
- LeetCode: Binary Tree Right Side View
- Leetcode: Binary Tree Right Side View
- 【leetcode】Binary Tree Right Side View(middle)
- LeetCode OJ Binary Tree Right Side View
- LeetCode | Binary Tree Right Side View
- LeetCode—Binary Tree Right Side View 二叉树层序遍历变形,Flatten Binary Tree to Linked List前序遍历变形
- LeetCode Binary Tree Right Side View : 思想上的基于队列的广度优先遍历,形式上的一个简单变种
- Leetcode 199 Binary Tree Right Side View
- Binary Tree Right Side View--LeetCode
- [Leetcode] Binary Tree Right Side View
- Leetcode: Binary Tree Right Side View
- [leetcode] Binary Tree Right Side View
- [leetcode]48 Binary Tree Right Side View