Untitled
unknown
plain_text
9 months ago
2.2 kB
4
Indexable
#include <bits/stdc++.h>
using namespace std;
class TreeNode {
public:
int val;
vector<TreeNode*> childrens;
TreeNode(int value){
val = value;
}
// void addChild(int value){
// TreeNode* child = new TreeNode(value);
// }
};
string rightSideView(TreeNode* root){
if(!root){
return "";
}
queue<TreeNode*> treeQueue;
treeQueue.push(root);
string result = "";
while(!treeQueue.empty()){
int size = treeQueue.size();
for(int i = 0; i < size; i++){
auto node = treeQueue.front();
treeQueue.pop();
if(i == size - 1){
result += to_string(node->val);
result += " ";
// cout << node->val << " ";
}
for(auto child : node->childrens){
treeQueue.push(child);
}
}
}
return result;
}
int main() {
TreeNode* root = new TreeNode(1);
TreeNode* child1 = new TreeNode(2);
TreeNode* child2 = new TreeNode(3);
TreeNode* child3 = new TreeNode(4);
TreeNode* child4 = new TreeNode(6);
root->childrens.push_back(child1);
root->childrens.push_back(child2);
root->childrens[0]->childrens.push_back(child3);
root->childrens[1]->childrens.push_back(child4);
cout << rightSideView(root) << "\n";
return 0;
}
// Given a general Tree print the right view
// 1
// 2 3
// 4 6
//
//
// result: 1 3 4
// Input: root node;
// TreeNode{
// val,
// childrens[]
// }
// string rightSideView(TreeNode* root){
// if(!root){
// return "";
// }
// queue<TreeNode*> treeQueue;
// treeQueue.push(root);
// string result = "";
// while(!treeQueue.empty()){
// int size = treeQueue.size();
// for(int i = 0; i < size; i++){
// auto node = treeQueue.front();
// treeQueue.pop();
// if(i == size - 1) result += node->val + " ";
// for(auto child : node->childrens){
// q.push(child);
// }
// }
// }
// return result;
// }
Editor is loading...
Leave a Comment