zoukankan      html  css  js  c++  java
  • Leetcode 199 Binary Tree Right Side View

    1.题目要求

    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].

    意思就是从右往左看,看到每一层最右边的那个数据。

    2.分析

    每一层最右边的那个数据,因此只需要按照层次遍历一遍这个二叉树,获取每一层的最右边的数据即可。
    二叉树层次遍历需要的数据结构是queue,现在是怎样判断每一层遍历结束,为了解决这个问题,可以再queue中插入一个标记NULL,读取到NULL,那说明NULL之前的那个数据就是该层最右边的数据。代码如下:

     1 class Solution {
     2 public:
     3     vector<int> rightSideView(TreeNode *root) {
     4         queue<TreeNode *> myQue;
     5         vector<int> res;        
     6         res.clear();
     7 
     8         if (NULL == root)
     9         {
    10             return res;
    11         }
    12         
    13         myQue.push(root);
    14         myQue.push(NULL);
    15         TreeNode *temp1,*temp2;
    16 
    17         while (true)
    18         {
    19             temp1 = myQue.front();
    20             myQue.pop();
    21             temp2 = myQue.front();
    22             //myQue.pop();
    23             if(NULL == temp1 && NULL == temp2)
    24                 break;
    25             if(NULL == temp1)
    26             {
    27                 myQue.push(NULL);//为下一层添加标记
    28                 continue;
    29 
    30             }
    31             if (NULL == temp2)//提取下一个指针,判断是否是标记NULL
    32             {
    33                 res.push_back(temp1->val);//保存最右边的值
    34             }            
    35             
    36             if(NULL != temp1->left)
    37                 myQue.push(temp1->left);
    38             if (NULL != temp1->right)
    39             {
    40                 myQue.push(temp1->right);
    41             }
    42         }
    43         return res;        
    44     }
    45 };

    提交Accepted,呵呵,第一次一次性通过啊。

    3.题目扩展,如果题目改成从左往右看呢?

    思路也是一样的,也是按照层次遍历,只不过每次是从右往左遍历。只需要将上面代码36-41行做一下调换即可,也就是先保存右子节点,再保存左子节点。

  • 相关阅读:
    08月24日总结
    08月23日总结
    08月22日总结
    装饰器
    卢菲菲最强大脑记忆训练法全套教程 01
    LeetCode 704 二分查找
    LeetCode 1480 一维数组的动态和
    NIO 总结
    LeetCode 881 救生艇
    url的组成部分
  • 原文地址:https://www.cnblogs.com/LCCRNblog/p/4392273.html
Copyright © 2011-2022 走看看