- 问题
Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
For example:
Given the following binary tree,
1 <--- / \ 2 3 <--- \ \ 5 4 <---
You should return
[1, 3, 4]
. - 解答
class Solution1 { public: vector<int> rightSideView(TreeNode* root) { vector<int> res; while(root) { res.push_back(root->val); TreeNode *f1; if(root->right==NULL) { f1=root->left; if(f1==NULL) break; } else f1=root->right; root=f1; } return res; } }; class Solution { public: vector<int> rightSideView(TreeNode *root) { vector<int> ans; if (root == nullptr) return ans; queue<TreeNode*> que; que.push(root); TreeNode* curr; while(!que.empty()) { int cnt = que.size(); for (int i = 0; i < cnt; i++) { curr = que.front(); que.pop(); if (curr->left) { que.push(curr->left); } if (curr->right) { que.push(curr->right); } } ans.push_back(curr->val); } return ans; } };
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交