二叉树的右视图
层次遍历,当每一层遍历时 i=size-1的时候,为该层次的最右点。压入结果
/** * 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; queue<TreeNode*> my_que; if(root == nullptr) return result; TreeNode* cur = root; my_que.push(cur); while(my_que.empty() != 1) { int size = my_que.size(); for (int i=0 ; i<size ; i++) { cur = my_que.front(); my_que.pop(); //此时为该层次的最右点 if(i == size-1) result.push_back(cur->val); if(cur->left != nullptr) my_que.push(cur->left); if(cur->right != nullptr) my_que.push(cur->right); } } return result; } };