您的位置:首页 > 其它

Leetcode NO.199 Binary Tree Right Side View

2015-05-08 04:43 316 查看
本题题目要求如下:

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);
	}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: