Skip to content
Programmingoneonone
Programmingoneonone

Learn everything about programming

  • Home
  • CS Subjects
    • Internet of Things (IoT)
    • Digital Communication
    • Human Values
    • Cybersecurity
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
  • HackerRank Solutions
    • HackerRank Algorithms Solutions
    • HackerRank C problems solutions
    • HackerRank C++ problems solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
Programmingoneonone
Programmingoneonone

Learn everything about programming

Leetcode Binary Tree Paths problem solution

YASH PAL, 31 July 2024

In this Leetcode Binary Tree Paths problem solution we have given the root of a binary tree, return all root-to-leaf paths in any order. A leaf is a node with no children.

Leetcode Binary Tree Paths problem solution

Problem solution in Python.

class Solution:
    def binaryTreePaths(self, root: TreeNode) -> List[str]:
        if root is None:
            return []
        path = str(root.val)
        res = []
        self.traverse(root,path,res)
        return res
    
    def traverse(self, root, path, res):
        if root.left is None and root.right is None:
            res.append(path)
        if root.left is not None:
            self.traverse(root.left, path+"->"+str(root.left.val), res)
        if root.right is not None:
            self.traverse(root.right, path+"->"+str(root.right.val), res)

Problem solution in Java.

public class Solution {
public List<String> binaryTreePaths(TreeNode root) {
    List<String> list = new ArrayList<String>();
    if(root == null)  return list;
    StringBuilder str = new StringBuilder();
    binaryHelper(root,list,str);
    return list;
}

private void binaryHelper(TreeNode root, List<String> list, StringBuilder str){
    if(root == null) return;
    StringBuilder newStr = new StringBuilder(str);
    if(newStr.length() != 0)
        newStr.append("->");
    newStr.append(root.val);
    if(root.left == null && root.right == null)
    {
        list.add(newStr.toString());
        return;
    }
        binaryHelper(root.left,list,newStr);
        binaryHelper(root.right,list,newStr);
}
}

Problem solution in C++.

vector<string> binaryTreePaths(TreeNode* root) 
    {
        if(root==NULL) return {};
        else
        {
            vector<string> lefty= binaryTreePaths(root->left);
            vector<string> righty= binaryTreePaths(root->right);
            vector<string> ans;
            string rooty=to_string(root->val);
            int l=lefty.size(), r=righty.size();
            if(l==0 and r==0) 
            {
                vector<string> v;
                v.push_back(rooty);
                return v;
            }
            for(int i=0;i<l;i++)
            {
                string s=rooty+"->"+lefty[i];
                ans.push_back(s);
            }
             for(int i=0;i<r;i++)
            {
                string s=rooty+"->"+righty[i];
                ans.push_back(s);
            }
            return ans;
        }
    }

Problem solution in C.

#define MAX_SIZE 1000

void pre_order_str(struct TreeNode *root, char ***res, int *res_size, char str[]) {
  
  if(NULL == root)
    return;

  char buf[MAX_SIZE];
  int append_size = 0;
  snprintf(buf, MAX_SIZE, "%d", root->val);
  append_size = strlen(buf);
  if(strnlen(str, MAX_SIZE) >= 1) {
    strncat(str, "->", MAX_SIZE);
    append_size += 2;
  }
  strncat(str, buf,MAX_SIZE);
  
  pre_order_str(root->left, res, res_size, str);
  pre_order_str(root->right, res, res_size, str);
  
  /*If leaf */
  if((!root->left) && (!root->right)) {    
    (*res_size)++;
    (*res) = realloc((*res), sizeof(char *) * (*res_size));
    int size = (*res_size) - 1;

    (*res)[size] = malloc(sizeof(char) * MAX_SIZE);
    strncpy((*res)[size], str, MAX_SIZE);
  }  
  
  /* when done with node remove ->val from str */
  str[strnlen(str, MAX_SIZE) - append_size] = '';  
}

char** binaryTreePaths(struct TreeNode* root, int* returnSize) {
  
  char **result = malloc(sizeof(char *) * 1);
  if(NULL == result) {
    *returnSize = 0;
    return NULL;
  }
  
  char str[MAX_SIZE];
  str[0] = '';
  
  pre_order_str(root, &result, returnSize, str);
  
  return result;
  
}

coding problems solutions

Post navigation

Previous post
Next post

Are you a student and stuck with your career or worried about real-time things, and don't know how to manage your learning phase? Which profession to choose? and how to learn new things according to your goal, and land a dream job. Then this might help to you.

Hi My name is YASH PAL, founder of this Blog and a Senior Software engineer with 5+ years of Industry experience. I personally helped 40+ students to make a clear goal in their professional lives. Just book a one-on-one personal call with me for 30 minutes for 300 Rupees. Ask all your doubts and questions related to your career to set a clear roadmap for your professional life.

Book session - https://wa.me/qr/JQ2LAS7AASE2M1

Pages

  • About US
  • Contact US
  • Privacy Policy

Follow US

  • YouTube
  • LinkedIn
  • Facebook
  • Pinterest
  • Instagram
©2026 Programmingoneonone | WordPress Theme by SuperbThemes