zoukankan      html  css  js  c++  java
  • [Leetcode] 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].

    层次遍历。

     1 /**
     2  * Definition for binary tree
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     vector<int> rightSideView(TreeNode *root) {
    13         vector<int> res;
    14         if (root == NULL) return res;
    15         queue<TreeNode*> Q;
    16         TreeNode *p;
    17         Q.push(root);
    18         int cnt1 = 1, cnt2;
    19         while (!Q.empty()) {
    20             cnt2 = 0;
    21             for (int i = 0; i < cnt1; ++i) {
    22                 p = Q.front();
    23                 Q.pop();
    24                 if (i == cnt1 - 1) res.push_back(p->val);
    25                 if (p->left) {
    26                     Q.push(p->left);
    27                     ++cnt2;
    28                 }
    29                 if (p->right) {
    30                     Q.push(p->right);
    31                     ++cnt2;
    32                 }
    33             }
    34             cnt1 = cnt2;
    35         }
    36         return res;
    37     }
    38 };
  • 相关阅读:
    joblib to implement multi-progress
    python排序
    回归评估:R2
    评估曲线
    模型融合:Stacking
    排列重要性
    单点登陆
    特征漂移检测
    python数组切片
    docker -ti
  • 原文地址:https://www.cnblogs.com/easonliu/p/4393265.html
Copyright © 2011-2022 走看看