给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。 示例:
/** * 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) { vector<int> vecRes; if(root == nullptr) return vecRes; queue<TreeNode *> q; q.push(root); while(!q.empty()) { TreeNode * pNode = nullptr; int nRightVal; int nSize = q.size(); bool isFind = false; for(int i=0;i<nSize;i++) { pNode = q.front(); q.pop(); if(pNode){ nRightVal = pNode->val; q.push(pNode->left); q.push(pNode->right); isFind = true; } else{ continue; } } if(isFind) vecRes.push_back(nRightVal); } return vecRes; } };