zoukankan      html  css  js  c++  java
  • [LeetCode] Binary Tree Right Side View

    A simple application of level-order traversal. Just push the last node in each level into the result.

    The code is as follows.

     1 class Solution {
     2 public:
     3     vector<int> rightSideView(TreeNode* root) {
     4         vector<int> right;
     5         if (!root) return right;
     6         queue<TreeNode*> toVisit;
     7         toVisit.push(root);
     8         while (!toVisit.empty()) {
     9             TreeNode* rightNode = toVisit.back();
    10             right.push_back(rightNode -> val);
    11             int num = toVisit.size();
    12             for (int i = 0; i < num; i++) {
    13                 TreeNode* node = toVisit.front();
    14                 toVisit.pop();
    15                 if (node -> left) toVisit.push(node -> left);
    16                 if (node -> right) toVisit.push(node -> right);
    17             }
    18         }
    19         return right;
    20     }
    21 };

    Well, the above code is of BFS. This problem can still be solved using DFS. The code is as follows. Play with it to see how it works :-)

     1 class Solution {
     2 public:
     3     vector<int> rightSideView(TreeNode* root) {
     4         vector<int> right;
     5         if (!root) return right;
     6         rightView(root, right, 0);
     7     }
     8 private:
     9     void rightView(TreeNode* node, vector<int>& right, int level) {
    10         if (!node) return;
    11         if (level == right.size())
    12             right.push_back(node -> val);
    13         rightView(node -> right, right, level + 1);
    14         rightView(node -> left, right, level + 1);
    15     }
    16 };
  • 相关阅读:
    统计候选人
    九宫格输入法
    前端同学面试准备
    1、单元格内换行诀窍、合并单元格、身份证、日期乱码
    读写锁
    混合锁、互斥锁
    原子操作、自旋锁
    pipeline httpmodule
    vm +cenos7+gitlab 02
    vm +cenos7+gitlab 01
  • 原文地址:https://www.cnblogs.com/jcliBlogger/p/4639135.html
Copyright © 2011-2022 走看看