• [leetcode] 199. Binary Tree Right Side View


    Medium

    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.

    Example:

    Input: [1,2,3,null,5,null,4]
    Output: [1, 3, 4]
    Explanation:
    
       1            <---
     /   
    2     3         <---
          
      5     4       <---

    题目大意:假设你站在一棵二叉树的右边,输出你看到的所有二叉树的节点值。

    方法:
    使用层序遍历。将每层中的最右一个值输出。

    使用队列,层序遍历。将二叉树的每一层的节点从左向右依次放入队列中,然后从头逐个弹出,并将这层节点的子节点压入队列中。每层的最后一个节点就是从右边能看到的节点,把这个节点值放入res向量中即可。循环该过程直至队列为空。
    代码如下:
    class Solution {
    public:
        vector<int> rightSideView(TreeNode* root) {
            if(!root)return {};
            vector<int> res;
            queue<TreeNode*> q{{root}};
            while(!q.empty()){
                int len=q.size();
                TreeNode* temp;
                for(int i=0;i<len;++i){
                    temp=q.front();
                    q.pop();
                    if(temp->left){q.push(temp->left);}
                    if(temp->right){q.push(temp->right);}
                }
                res.push_back(temp->val);
            }
            return res;
        }
    };
  • 相关阅读:
    MVC中使用AuthorizeAttribute做身份验证操作
    Entity Framework 5.0 Code First全面学习
    AngularJs学习教程
    安装完Oracle数据库,给scott账户解锁方法
    Signalr学习教程
    javascript学习教程【Qi Fei】
    并行开发
    MongoDB教程【一】
    统计学习概念
    自学Python的点滴
  • 原文地址:https://www.cnblogs.com/cff2121/p/11880970.html
Copyright © 2020-2023  润新知