zoukankan      html  css  js  c++  java
  • 【LeetCode】199. Binary Tree Right Side View

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

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

    层次遍历,到每一层最后一个节点,即装入ret

    每层最后一个节点的判断:

    (1)队列为空

    (2)下一个待遍历节点在下一层

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    struct Node
    {
        TreeNode* tnode;
        int level;
        
        Node(TreeNode* t, int l): tnode(t), level(l) {}
    };
    
    class Solution {
    public:
        vector<int> rightSideView(TreeNode *root) {
            vector<int> ret;
            if(root == NULL)
                return ret;
            queue<Node*> q;
            int curLevel = 0;
            Node* rootNode = new Node(root,0);
            q.push(rootNode);
            
            while(!q.empty())
            {
                Node* front = q.front();
                q.pop();
                
                if(q.empty() || q.front()->level > front->level)
                //last node of current level
                    ret.push_back(front->tnode->val);
                
                if(front->tnode->left)
                {
                    Node* leftNode = new Node(front->tnode->left, front->level+1);
                    q.push(leftNode);
                }
                
                if(front->tnode->right)
                {
                    Node* rightNode = new Node(front->tnode->right, front->level+1);
                    q.push(rightNode);
                }
            }
            return ret;
        }
    };

  • 相关阅读:
    ZendStudio 解决svn导出项目乱码问题
    Linux常用命令
    php类与对象
    Apache shutdown unexpectedly启动错误解决方法
    php构造函数和析构函数
    MySQL基本概念
    Javascript中常用事件的命名
    网页布局
    页面的自动滚动效果
    表单验证和事件(2)
  • 原文地址:https://www.cnblogs.com/ganganloveu/p/4418065.html
Copyright © 2011-2022 走看看