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]
.
题意:给定一颗二叉树,假设你站在二叉树的右边。从你的方向看出去,求你能见到的所有节点的值。
分类:二叉树
解法1:层次遍历。每次保留每层的最后一个节点就可以了。
/**
* 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> res = new ArrayList<Integer>();
if(root==null) return res;
List<TreeNode> queue = new ArrayList<TreeNode>();
int low = 0;
int high = 1;
int ceng = 0;
queue.add(root);
while(low<high){
TreeNode cur = queue.get(low);
if(cur.left!=null){
queue.add(cur.left);
high++;
}
if(cur.right!=null){
queue.add(cur.right);
high++;
}
if(ceng==low){
res.add(cur.val);
ceng = high-1;
}
low++;
}
return res;
}
}
解法2:层次遍历。和解法1思路一样,只是代码更加精简。
/**
* 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) {
LinkedList<TreeNode> queue = new LinkedList<TreeNode>();//队列,用于层次遍历
List<Integer> res = new ArrayList<Integer>();//结果
if(root==null) return res;
int level = 1;
queue.add(root);
while(queue.size()>0){
TreeNode node = queue.poll();
if(node.left != null)
queue.add(node.left);
if(node.right != null)
queue.add(node.right);
if(--level == 0){
level = queue.size();
res.add(node.val);
}
}
return res;
}
}