Leetcode NO.199 Binary Tree Right Side View

来源:互联网 发布:xp下安装linux双系统 编辑:程序博客网 时间:2024/05/16 02:05

本题题目要求如下:

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,我感觉现在我dfs用的还算是比较熟练了。。。

我的思路未必是最简的,毕竟挺耗空间的。。但是时间复杂度还是不错的。。

思路如下:

  • 常规的DFS,只不过在DFS上面加入了层数,比如1在第一层,2,3在第二层。。。都存在二维数组中,第一维是level
  • 这样跑DFS,recursive中,优先搜索左边的node,这样会保证同一层的访问顺序必然是从左到右。。。
  • 然后把每层对应数组的最后一个数提取出来,就可以返回答案
代码如下:

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    vector<int> rightSideView(TreeNode* root) {        dfs(root, 0);        vector<int> ret;        for (int i = 0; i < res.size(); ++i) {        ret.push_back(res[i].back());        }        return ret;    }private:vector<vector<int>> res;void dfs(TreeNode* root, int level) {if (root == NULL)return;if (level == res.size()) {vector<int> tmp;res.push_back(tmp);}res[level].push_back(root->val);dfs(root->left, level+1);dfs(root->right, level+1);}};


0 0
原创粉丝点击