[关闭]
@gump88 2016-10-09T07:31:48.000000Z 字数 738 阅读 1072

title: LeetCode题解

LeetCode:Binary Tree Right Side View

date: 2016-10-09 20:09:12

[LeetCode,算法]


题目见Binary Tree Right Side View,从右侧观察树见到的树的第一个节点,从上到下输出出来,思路就是层序遍历,将每层的结点加入数组。具体代码见下:

  1. /**
  2. * Definition for a binary tree node.
  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. List<Integer> res = new ArrayList<>();
  13. if(root == null) {
  14. return res;
  15. }
  16. List<TreeNode> nodelist = new ArrayList<>();
  17. nodelist.add(root);
  18. int cur = 0,last = nodelist.size();
  19. while(cur < nodelist.size()){
  20. last = nodelist.size();
  21. res.add(nodelist.get(last-1).val);
  22. for(;cur < last;cur++) {
  23. TreeNode temp = nodelist.get(cur);
  24. if(temp.left != null) {
  25. nodelist.add(temp.left);
  26. }
  27. if(temp.right != null) {
  28. nodelist.add(temp.right);
  29. }
  30. }
  31. }
  32. return res;
  33. }
  34. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注