leetcode199. 二叉树的右视图

tech2022-07-13  170

给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。 示例:

/** * 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; } };
最新回复(0)