leetcode-二叉树的右视图

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        //思路:显然需要得到每一层的数据,用队列
        List<Integer> retlist = new LinkedList<>();
        if(root == null){
            return retlist;
        }
        Queue<TreeNode> runningQueue = new LinkedList<>();
        runningQueue.add(root);
        while(!runningQueue.isEmpty()){

            Queue<TreeNode> temrunningQueue = new LinkedList<>();
            while(!runningQueue.isEmpty()){
                TreeNode polltreenode = runningQueue.poll();
                if(polltreenode.left!=null){
                    temrunningQueue.add(polltreenode.left);
                }
                if(polltreenode.right != null){
                    temrunningQueue.add(polltreenode.right);
                }
                if(runningQueue.isEmpty()){
                    retlist.add(polltreenode.val);
                }
            }
            runningQueue = temrunningQueue;
        }
        return retlist;
    }
}

没什么难度。使用queue记录每一层,然后找到最右侧的元素即可(被poll()的最后一个元素)

发布了48 篇原创文章 · 获赞 0 · 访问量 4335

猜你喜欢

转载自blog.csdn.net/weixin_41327340/article/details/103753688
今日推荐