LeetCode199. 二叉树的右视图

二叉树层次遍历,用一个数组记录每一层的最右边的元素。

class Solution {
public:
    vector<int> rightSideView(TreeNode* root) {
        if(root == NULL) {
            return {};
        }
        vector<int> res;
        queue<TreeNode*> q;
        q.push(root);
        while(!q.empty()) {
            int size = q.size();
            for(int i = 0; i < size; ++i) {
                TreeNode* temp = q.front();
                q.pop();
                if(i == size - 1) {                                    
                    res.push_back(temp -> val);            //记录一下这一层的最右边的元素
                }
                if(temp -> left != NULL) {
                    q.push(temp -> left);
                }
                if(temp -> right != NULL) {
                    q.push(temp -> right);
                }
            }
        }
        return res;
    }
};
原文地址:https://www.cnblogs.com/linrj/p/13433964.html