Easy code, 300ms, using (Override) toString()


  • 0
    N

    class A is just used to display the data, like 1->2->3.So you can deal with the negative number as well

    class A {
     public ArrayList<Integer> data = new ArrayList<Integer>();
     public String toString() {
         if (data.size() > 1) {
             StringBuilder s = new StringBuilder();
             s.append(data.get(0));
             for (int i = 1; i < data.size(); i++) {
                s.append("->" + data.get(i));
             }
             return s.toString();
         } else if (data.size() == 1){
             return data.get(0) + "";
         } 
         return "";
     }}
    

    The second step is do some recursion.

    public class Solution {
    ArrayList hold = new ArrayList<String>();
    A a = new A();
    
    public List<String> binaryTreePaths(TreeNode root) {
        if (root == null) return hold;
        a.data.add(root.val);
        binaryTree(root);
        return hold ;
        
    }
    
    private void binaryTree(TreeNode root) {
        if (root.left == null && root.right == null) {
            hold.add(a.toString());
            return;
        }
        
        if (root.left != null) {
            a.data.add(root.left.val);
            binaryTree(root.left);
            a.data.remove(a.data.size() - 1);
        }
        
        if (root.right != null) {
            a.data.add(root.right.val);
            binaryTree(root.right);
            a.data.remove(a.data.size() - 1);
        }
    }
    

    }


Log in to reply
 

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