Java Solution using ArrayList


  • 0
    Y

    class Solution {
    class ArrayListAnySize<E> extends ArrayList<E> {
    @Override
    public void add(int index, E element){
    if(index >= 0 && index <= size()){
    super.add(index, element);
    return;
    }
    int insertNulls = index - size();
    for(int i = 0; i < insertNulls; i++){
    super.add(null);
    }
    super.add(element);
    }
    }

    class Node {
        int data;
        Node left;
        Node right;
        Node (int data) {
            this.data=data;
        }
    }
    
    public int calculateSum(Node root,int sum) {
        if(root==null) return sum;
        if(root.left==null&&root.right==null) return root.data+sum;
        int result=0;
        if(root.left!=null) {
        	result=calculateSum(root.left,sum+root.data);
        }
        if(root.right!=null) {
        result=result+calculateSum(root.right,sum+root.data);
        }
        return result;
    }
    
    public int pathSum(int[] nums) {
        
        ArrayListAnySize<ArrayListAnySize<Node>> list=new ArrayListAnySize<ArrayListAnySize<Node>>();
        Node root=null;
        Node parent=null;
        
        //Building Tree
        for(int i=0;i<nums.length;i++) {
            int value=(nums[i]%100)%10;
            int p=(nums[i]/10)%10;
            int d=nums[i]/100;
    
            ArrayListAnySize<Node> innerList=null;
            if(list.size()<d) {
                innerList=new ArrayListAnySize<Node>();
                list.add(innerList);
            }
            else {
                innerList=list.get(d-1);
            }
            if(root==null) {
                root=new Node(value);
                innerList.add(root);
                continue;
            }else {
                Node temp=new Node(value);
                parent=list.get(d-2).get((p-1)/2);
                if(p%2==0) {
                    parent.right=temp;
                }else {
                    parent.left=temp;
                }
                innerList.add((p-1),temp);
            }
        }
        
        int result=calculateSum(root,0);
        return result;
        
    }
    

    }


Log in to reply
 

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