赞
踩
思路:我们可以对二叉树进行层次遍历,那么对于每层来说,最右边的结点一定是最后被遍历到的。二叉树的层次遍历可以用广度优先搜索实现。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public List<Integer> rightSideView(TreeNode root) { List<Integer> list = new ArrayList(); Deque<TreeNode> deque = new LinkedList<>(); if(root != null){ deque.offer(root); } while(!deque.isEmpty()){ int size = deque.size(); for(int i = 0; i < size; i++){ TreeNode node = deque.poll(); if(node.left != null){ deque.offer(node.left); } if(node.right != null){ deque.offer(node.right); } // 层序遍历到每一层的最后一个节点加入list数组 if(i == size - 1){ list.add(node.val); } } } return list; } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。