zoukankan      html  css  js  c++  java
  • 【Binary Tree Right Side View 】cpp

    题目:

    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].

    Credits:
    Special thanks to @amrsaqr for adding this problem and creating all test cases.

    代码:

    /**
     * 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) {
                vector<int> ret;
                queue<TreeNode*> curr;
                queue<TreeNode*> next;
                if (root) { curr.push(root); ret.push_back(root->val); }
                while ( !curr.empty() )
                {
                    while ( !curr.empty() )
                    {
                        TreeNode* tmp = curr.front();
                        curr.pop();
                        if ( tmp->left ) next.push(tmp->left);
                        if ( tmp->right ) next.push(tmp->right);
                    }
                    if (!next.empty()) ret.push_back(next.back()->val);
                    swap(next,curr);
                }
                return ret; 
        }
    };

    tips:

    BFS算法,level order traversal binary tree

    每次保留每一个level的最右一个元素的值。

  • 相关阅读:
    关于医保卡的正确使用
    mysql rpm安装,以及修改charset
    hql小经验
    工资构成
    distinct 与order by 一起用
    服务器设置浏览器的文档模式
    项目管理
    show processlist 各个状态说明
    sql 查询优化
    定时器备份数据库
  • 原文地址:https://www.cnblogs.com/xbf9xbf/p/4646305.html
Copyright © 2011-2022 走看看