Binary Tree Right Side View Solutions in C++
Number 199
Difficulty Medium
Acceptance 54.2%
Link LeetCode
Other languages Go
Solutions
C++ solution by haoel/leetcode
// Source : https://leetcode.com/problems/binary-tree-right-side-view/// Author : Hao Chen// Date : 2015-04-07/*** Definition for binary tree* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode(int x) : val(x), left(NULL), right(NULL) {}* };*/class Solution {public:void rightSideViewHelper(TreeNode* root, int level, vector<int>& result) {if (root == NULL) return;if ( result.size() < level ) result.push_back(root->val);rightSideViewHelper(root->right, level+1, result);rightSideViewHelper(root->left, level+1, result);}void rightSideViewHelper(TreeNode* root, vector<int>& result) {if (root==NULL) return;vector<TreeNode*> stack;vector<int> level;stack.push_back(root);level.push_back(1);while (stack.size()>0) {TreeNode* r = stack.back(); stack.pop_back();int l = level.back(); level.pop_back();if ( result.size() < l ) {result.push_back(r->val);}if (r->left) {stack.push_back(r->left);level.push_back(l+1);}if (r->right) {stack.push_back(r->right);level.push_back(l+1);}}}vector<int> rightSideView(TreeNode *root) {vector<int> result;if (rand()%2){rightSideViewHelper(root, 1, result);}else{rightSideViewHelper(root, result);}return result;}};
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/binary-tree-right-side-view//// Author : liuyubobobo/// Time : 2019-09-26#include <iostream>#include <vector>using namespace std;/// BFS/// Time Complexity: O(n)/// Space Complexity: O(n)/// 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> res;if(!root) return res;vector<TreeNode*> cur = {root};while(cur.size()){res.push_back(cur.back()->val);vector<TreeNode*> next;for(TreeNode* node: cur){if(node->left) next.push_back(node->left);if(node->right) next.push_back(node->right);}cur = next;}return res;}};int main() {return 0;}
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/binary-tree-right-side-view//// Author : liuyubobobo/// Time : 2019-09-26#include <iostream>#include <vector>using namespace std;/// DFS/// Time Complexity: O(n)/// Space Complexity: O(h)/// 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 {private:vector<int> res;public:vector<int> rightSideView(TreeNode* root) {if(!root) return res;dfs(root, 0);return res;}private:void dfs(TreeNode* node, int d){if(res.size() <= d) res.push_back(0);res[d] = node->val;if(node->left) dfs(node->left, d + 1);if(node->right) dfs(node->right, d + 1);}};int main() {return 0;}