问题描述:
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.
Example:
Input: [1,2,3,null,5,null,4] Output: [1, 3, 4] Explanation: 1 <--- / \ 2 3 <--- \ \ 5 4 <---
源码:
这个题目其实有点题意不清,我就简单再说一下。题目意思指的是找到每一层的最右边的元素。
这样就简单明了了,只需要层次遍历,然后把每行的最后一个元素加进去即可,层次遍历可以参考leetcode【107】Binary Tree Level Order Traversal II
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> result;
if(!root) return result;
int cur=1, next=0;
queue<TreeNode*> st;
st.push(root);
while(!st.empty()){
TreeNode* tmp = st.front();
st.pop();
cur--;
if(tmp->left){
next++; st.push(tmp->left);
}
if(tmp->right){
next++; st.push(tmp->right);
}
if(cur == 0){
result.push_back(tmp->val);
cur = next;
next = 0;
}
}
return result;
}
};
翻了一下Solution区(好不容易有一题对非会员开放,咱能不看嘛),提供了两种方法DFS和BFS。感觉很麻烦,而且效率很低,我比较倾向于DFS,在此就演示一下DFS吧,感兴趣的读者可以自己试一下BFS。(用一个hash表维持每个depth的最后边的元素)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> result;
if(!root) return result;
stack<TreeNode*> st;
stack<int> depth;
unordered_map<int, int> hash;
int maxdep = 0;
st.push(root);
depth.push(0);
hash[0] = root->val;
while(!st.empty()){
TreeNode* tmp = st.top();
st.pop();
int tmp_dep = depth.top();
depth.pop();
maxdep = max(maxdep, tmp_dep);
if(!hash.count(tmp_dep)) hash[tmp_dep] = tmp->val;
if(tmp->left){
st.push(tmp->left); depth.push(tmp_dep+1);
}
if(tmp->right){
st.push(tmp->right); depth.push(tmp_dep+1);
}
}
for(int i=0; i<=maxdep; i++){
result.push_back(hash[i]);
}
return result;
}
};