fork download
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. // Node Structure
  6. class Node {
  7. public:
  8. int data;
  9. Node* left;
  10. Node* right;
  11.  
  12. Node(int x) {
  13. data = x;
  14. left = right = nullptr;
  15. }
  16. };
  17.  
  18. // Recursive function to find left view
  19. void recLeftView(Node* root, int level, vector<int>& result) {
  20. if (root == nullptr) return;
  21.  
  22. // first node of current level
  23. if (level == result.size()) {
  24. result.push_back(root->data);
  25. }
  26.  
  27.  
  28. recLeftView(root->right, level + 1, result);
  29.  
  30. recLeftView(root->left, level + 1, result);
  31. }
  32.  
  33. // Function which return left view of binary tree
  34. vector<int> leftView(Node* root) {
  35. vector<int> result;
  36. recLeftView(root, 0, result);
  37. return result;
  38. }
  39.  
  40. int main() {
  41. // Create binary tree
  42.  
  43. // 1
  44. // / \
  45.   // 2 3
  46. // /
  47. // 4
  48. // \
  49.   // 5
  50.  
  51. Node* root = new Node(1);
  52. root->left = new Node(2);
  53. root->right = new Node(3);
  54. root->right->left = new Node(4);
  55. root->right->left->right = new Node(5);
  56.  
  57. vector<int> view = leftView(root);
  58. for (int val : view)
  59. cout << val << " ";
  60. }
Success #stdin #stdout 0s 5320KB
stdin
Standard input is empty
stdout
1 3 4 5