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

    思路:dfs。每次优先遍历右子树。同时需要记录当前所处的深度,当第一次进入一个深度时,就将该值存入结果。因为我们每次都是优先遍历右子树,因此这样做一定是最右侧能看到的节点。

     1 class Solution {
     2 public:
     3     void help(vector<int>& res, TreeNode* root, int depth)
     4     {
     5         if (!root) return;
     6         if (res.size() < depth + 1)
     7             res.push_back(root->val);
     8         help(res, root->right, depth + 1);
     9         help(res, root->left, depth + 1);
    10     }
    11     vector<int> rightSideView(TreeNode* root) {
    12         vector<int> res;
    13         help(res, root, 0);
    14         return res;
    15     }
    16 };
  • 相关阅读:
    SQL操作符的优化
    Oracle 模糊查询 优化
    Mysql中的语句优化
    SQL优化
    Pro Git读书笔记
    前端工程化
    前端工程化
    前端工程化
    前端工程化
    前端工程化
  • 原文地址:https://www.cnblogs.com/fenshen371/p/5165441.html
Copyright © 2011-2022 走看看