@gump88
2016-10-09T15:31:48.000000Z
字数 738
阅读 1138
title: LeetCode题解
date: 2016-10-09 20:09:12
[LeetCode,算法]
题目见Binary Tree Right Side View,从右侧观察树见到的树的第一个节点,从上到下输出出来,思路就是层序遍历,将每层的结点加入数组。具体代码见下:
/**
* 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<>();
if(root == null) {
return res;
}
List<TreeNode> nodelist = new ArrayList<>();
nodelist.add(root);
int cur = 0,last = nodelist.size();
while(cur < nodelist.size()){
last = nodelist.size();
res.add(nodelist.get(last-1).val);
for(;cur < last;cur++) {
TreeNode temp = nodelist.get(cur);
if(temp.left != null) {
nodelist.add(temp.left);
}
if(temp.right != null) {
nodelist.add(temp.right);
}
}
}
return res;
}
}