Binary Tree Paths @LeetCode

PROBLEM :

Given a binary tree, return all root-to-leaf paths.

For example, given the following binary tree:

   1
 /   \
2     3
 \
  5
 
All root-to-leaf paths are:

["1->2->5", "1->3"]

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

/**
 * 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<string> binaryTreePaths(TreeNode* root) {
        vector<string> vec ;
        if(root==NULL)
            return vec ;
           
        string str="" ;
        CheckAllPaths(root,str,vec) ;
        return vec ;
    }
   
    void CheckAllPaths(TreeNode *root,string str,vector<string> &vec){
        if(root==NULL)
            return ;
           
        if(str=="")  
            str+=to_string(root->val) ;
        else{
            str+="->" ;
            str+=to_string(root->val) ;
        }
       
        if(root->left==NULL&&root->right==NULL)
            vec.push_back(str) ;
           
        CheckAllPaths(root->left,str,vec) ;
        CheckAllPaths(root->right,str,vec) ;
    }
};

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )