设为首页 加入收藏

TOP

leetcode:Binary Tree Right Side View
2015-11-21 01:04:27 来源: 作者: 【 】 浏览:1
Tags:leetcode:Binary Tree Right Side View

一、 题目

给你一个二叉树,假设几就站在树的后边,那么此时你就只能看到最右边的节点了。

例如:

1 <---

/ \

2 3 <---

\ \

5 4 <---

返回值就是[1,3,4]

二、 分析

对于树的遍历,我们通常会使用DFS或BFS,这个题目其实同样是遍历,不过呢,我们只记录下来每一行最右边的节点即可。我第一个思路是每次只访问右节点,但仔细一想,并不一定所有的都是这种情况的,例如或许最右边的节点在左半部分的。马上否定了这个思路,想想不管怎样都得是要遍历所有节点的,不过我们是按照变相的前序遍历,即当前节点-右节点-左节点的顺序,每次都将他们放进队列,但是取的时候我们只记录下第一个节点即可,其他的都释放掉。

?

?

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    
    vector
  
    rightSideView(TreeNode *root) {
        vector
   
     res; if(root == NULL) return res; queue
    
      nQueue; TreeNode *node = root; nQueue.push(node); while(!nQueue.empty()){ int size = nQueue.size(); for(int i = 0; i < size; i++){ node = nQueue.front(); nQueue.pop(); if(i == 0) res.push_back(node->val); if(node->right) nQueue.push(node->right); if(node->left) nQueue.push(node->left); } } return res; } };
    
   
  


?

?

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇URAL - 1792 Hamming Code(枚举) 下一篇Partition List -- leetcod

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: