From 3db54b6a519e8493295af36bcc14ec8e70b6b065 Mon Sep 17 00:00:00 2001 From: Ayushman Singh Date: Thu, 17 Aug 2023 19:24:19 +0530 Subject: [PATCH] Cplusplus - Tree- Binary Tree Right side View --- .../Trees/Binary-Tree-Right-Side-View.cpp | 103 ++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 algorithms/CPlusPlus/Trees/Binary-Tree-Right-Side-View.cpp diff --git a/algorithms/CPlusPlus/Trees/Binary-Tree-Right-Side-View.cpp b/algorithms/CPlusPlus/Trees/Binary-Tree-Right-Side-View.cpp new file mode 100644 index 00000000..479c51d5 --- /dev/null +++ b/algorithms/CPlusPlus/Trees/Binary-Tree-Right-Side-View.cpp @@ -0,0 +1,103 @@ +//Print the list of all the nodes visible when the binary tree is observed from the right side. +//Starting from the top , i.e. the root node. + +#include +#include +#include + +using namespace std; + +// Node structure for tree +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + + TreeNode(int val) { + this->val = val; + left = nullptr; + right = nullptr; + } +}; + + +void rightsideview(TreeNode * root) +{ + vector ans; + + TreeNode* curr; + + curr=root; + queue que; + + que.push(curr); + + while(!que.empty()) + { + int s=que.size(); + + for(int i=0;ileft!=NULL) + que.push(curr->left); + if(curr->right!=NULL) + que.push(curr->right); + } + + ans.push_back(curr->val); + } + + + + for(int i=0;ileft=new TreeNode(2); + root->right= new TreeNode(3); + + curr=root->right; + curr->left= new TreeNode(4); + + curr=root->left; + + curr->left= new TreeNode(5); + + curr->left->left= new TreeNode(6); + + curr=curr->left->left; + + curr->left= new TreeNode(7); + curr->left->right= new TreeNode(8); + curr->left->left=new TreeNode(9); + + + // 1 + // / \ + // 2 3 + // / / + // 5 4 + // / + // 6 + // / + // 7 + // / \ + // 9 8 + + + // The Output Should be -> 1, 3, 4, 6, 7, 8; + + + + rightsideview(root); // This function prints the result; + return 0; +}