• 【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;
        }
    };

  • 相关阅读:
    SharePoint母板页更改
    SharePoint的一些基本操作
    百度地图
    内存管理
    根据文字的个数,label自动适应高度
    navgationBar
    接收服务器上的图片,可以用webview或者 imageview
    iOS 自带的解析json的类。
    改变uilable uibutton等的字体颜色、大小。
    Nsstring和NSdata的编码转换
  • 原文地址:https://www.cnblogs.com/ganganloveu/p/4418065.html
Copyright © 2020-2023  润新知