Java PreOrder welcome discuss


  • 0
    K

    My Problem:``
    1,ArrayList<ArrayList<Integer>> list = new... ;
    this statement is not permitted;
    2,leaf node is judged by if(node.left ==null && node.right == null); And I have made a mistake to judge non-leaf-node;
    3,It's a good method: ArrayList<Integer> newlist = new ArrayList<Integer>(list); list is an old List to compromise newlist ;`
    my code:

    /**
    
    • Definition for binary tree

    • public class TreeNode {

    • int val;
      
    • TreeNode left;
      
    • TreeNode right;
      
    • TreeNode(int x) { val = x; }
      
    • }
      */
      public class Solution {
      ArrayList<List<Integer>> result = new ArrayList<List<Integer>>();
      int sum = 0;
      public List<List<Integer>> pathSum(TreeNode root, int sum) {
      this.sum = sum;
      List list = new ArrayList<Integer>();

       PreOrder(root,list);
       return result;
      

      }
      public void PreOrder(TreeNode node,List<Integer> list){
      if( node != null){
      //visit
      ArrayList<Integer> newlist = new ArrayList<Integer>(list);
      newlist.add(node.val);
      if(node.left == null && node.right == null){// leaf node
      if(getsum(newlist) == sum){
      result.add(newlist);
      }
      }

            PreOrder(node.left,newlist);
            PreOrder(node.right,newlist);
        }
    }
    public int getsum(List<Integer> list){
        int count = 0 ;
        for(Integer i : list){
            count+=i;
        }
        return count;
    }
    

    }


Log in to reply
 

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