zoukankan      html  css  js  c++  java
  • leetcode 199. Binary Tree Right Side View

    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.

    For example:
    Given the following binary tree,
       1            <---
     /   
    2     3         <---
          
      5     4       <---
    You should return [1, 3, 4].
    

    树的层序遍历,保留每层的最后一个

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        vector<int> rightSideView(TreeNode* root) {
            queue<TreeNode*> q;
            vector<int> v;
            if (root == nullptr) return v;
            q.push(root);
            while(!q.empty()) {
                int x = q.size();
                int tmp;
                for (int i = 0; i < x; ++i) {
                    TreeNode* u = q.front();q.pop();
                    if (u->left != nullptr) q.push(u->left);
                    if (u->right != nullptr) q.push(u->right);
                    tmp = u->val;
                }
                v.push_back(tmp);
            }
            return v;
        }
    };
    
  • 相关阅读:
    网页动画
    浮动
    定位
    盒子模型
    表单
    2017年07月05号课堂笔记
    2017年07月07号课堂笔记
    2017年07月03号课堂笔记
    2017年06月30号课堂笔记
    2017年06月28号课堂笔记
  • 原文地址:https://www.cnblogs.com/pk28/p/7649370.html
Copyright © 2011-2022 走看看