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

    Example:

    Input: [1,2,3,null,5,null,4]
    Output: [1, 3, 4]
    Explanation:
    
       1            <---
     /   
    2     3         <---
          
      5     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) {
            vector<int> ret;
            if(!root) return ret;
            queue<TreeNode*> q;
            TreeNode* nextStart = NULL;
            q.push(root);
            while(!q.empty()){
                TreeNode* cur = q.front();
                q.pop();
                if(!nextStart || nextStart == cur){
                    nextStart = cur->left ? cur->left : cur->right; 
                }
                if(cur->left) q.push(cur->left);
                if(cur->right) q.push(cur->right);
                
                if(q.empty() || (!q.empty() && nextStart == q.front())){
                    ret.push_back(cur->val);
                }
                    
            }
            return ret;
        }
    };
  • 相关阅读:
    Oracle 11g数据库详解
    1.Oracle数据库查看用户锁表和对表解锁的sql语句
    ORACLE性能优化- Buffer cache 的调整与优化
    excel数据生成sql insert语句
    Python_二叉树
    Python_自定义栈
    Python_内置四种队列
    Python_重写集合
    python_pycharm下拉前置标示
    python_形参何时影响实参
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/9452659.html
Copyright © 2011-2022 走看看