199. 二叉树的右视图
解题思路:
使用层序遍历,输出每一层最右边的节点即可。
C++:
/** * 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) { queue<TreeNode*> nodeQueue; nodeQueue.push(root); vector<int> rightView; if (root == nullptr) return rightView; while (!nodeQueue.empty()) { int size = nodeQueue.size(); rightView.push_back(nodeQueue.front()->val); for (int i = 0; i < size; ++i) { auto node = nodeQueue.front(); nodeQueue.pop(); if (node->right) { nodeQueue.push(node->right); } if (node->left) { nodeQueue.push(node->left); } } } return rightView; } };