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 };

 

posted @ 2016-01-28 10:43  fenshen371  阅读(172)  评论(0编辑  收藏  举报