Binary Tree Right Side View in C++

C++Server Side ProgrammingProgramming

Suppose we have a binary tree, if we see the tree from right side, then we can see some elements of it. we have to display those elements. So if the tree is like −


To solve this, we will follow these steps −

  • We will create one helping method for dfs. This will take tree_node, an array to hold answers, and level. The level is initially 0. The dfs will work like below −

  • if node is null, then return

  • if level = length of the answer array, then insert value of node into the ans array

  • dfs(right of the node, ans, level + 1)

  • dfs(left of the node, ans, level + 1)

  • From the main function call the dfs() using the root of the tree and one blank array, the level is initially 0, so this will be dfs(root, ans)

Let us see the following implementation to get better understanding −

Example

class Solution {
   public:
   void dfs(TreeNode* node, vector <int>& ans, int level = 0){
      if(!node) return;
      if(level == ans.size())ans.push_back(node->val);
      dfs(node->right, ans, level + 1);
      dfs(node->left, ans, level + 1);
   }
   vector<int> rightSideView(TreeNode* root) {
      vector <int> ans;
      dfs(root, ans);
      return ans;
   }
};

Input

[1,2,3,null,5,null,4]

Output

[1,3,4]
raja
Published on 05-Feb-2020 09:47:44
Advertisements