AC easy understanding java solution


  • 0
    J
    public class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> path = new ArrayList<String>();
        if(root == null) return path;
        String res = ""+root.val;
        if(root.right==null&&root.left==null){
            path.add(res);
            return path;
        }
        findPath(root.right,path,res);
        findPath(root.left,path,res);
        return path;
    }
    
    public void findPath(TreeNode root,List path,String res){
         if(root==null){
             return;
         }
         //just add the result at the final stage---the node is a leaf
         if(root.right==null&&root.left==null){
             res+="->"+root.val;
             path.add(res);
         }
        
         res+="->"+root.val;
         findPath(root.right,path,res);
         findPath(root.left,path,res);
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.