您的位置:首页 > 其它

[LeetCode]Binary Tree Right Side View

2015-07-26 20:19 357 查看
解题思路:

宽度搜索,记录每一个node的height,当遇到当前node的height与前一个node的height不一样时,说明前一个node是那个height level的最右边的node,可以把val加入return vector

/**
* 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) {
if ( root == NULL ) return {};

queue<TreeNode* > st;
queue<int> stHeight;
int preHeight = 0;
TreeNode* preNode = root;

vector<int> ret;

st.push(root);
stHeight.push(0);

while(!st.empty()){
TreeNode* curNode = st.front(); st.pop();
int curHeight = stHeight.front(); stHeight.pop();
if (curNode != NULL){
if (curHeight != preHeight){
ret.push_back(preNode->val);
}
preNode = curNode;
preHeight = curHeight;

st.push(curNode->left);
stHeight.push(curHeight+1);
st.push(curNode->right);
stHeight.push(curHeight+1);
}
}

if (preNode != NULL){
ret.push_back(preNode->val);
}
return ret;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: