Skip to content
This repository was archived by the owner on Aug 14, 2024. It is now read-only.

Latest commit

 

History

History
48 lines (38 loc) · 888 Bytes

257.md

File metadata and controls

48 lines (38 loc) · 888 Bytes

257. Binary Tree Paths

Description

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"]

Code

public class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> res = new ArrayList<>();
        if(root == null)
            return res;
        findPaths(root, res, "");
        return res;
    }
    
    void findPaths(TreeNode root,  List<String> res, String sb){
        if(root.left == null && root.right == null){
            res.add(sb + root.val);
        } 
        if(root.left != null){
            findPaths(root.left, res, sb + root.val + "->");
        }
        if(root.right != null){
            findPaths(root.right, res, sb + root.val + "->");
        }
    }
}