思路
方法:层序遍历
保存层序遍历每一层的最后一个数字即可。
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 * }; 11 */ 12 class Solution { 13 public: 14 vector<int> rightSideView(TreeNode* root) { 15 vector<int> res; 16 if(root == NULL) 17 return res; 18 19 //层序遍历 20 queue<TreeNode*> q; 21 q.push(root); 22 TreeNode* t; 23 while(!q.empty()) { 24 int qsize = q.size(); 25 for(int i = 0; i < qsize; ++i) { 26 t = q.front(); 27 //保存每一层的最后一个结点的值 28 if(i == qsize-1) { 29 res.push_back(t->val); 30 } 31 if(t->left) q.push(t->left); 32 if(t->right) q.push(t->right); 33 q.pop(); 34 } 35 } 36 37 return res; 38 } 39 };
复杂度分析:
时间复杂度:O(n)
空间复杂度:O(n)