Find paths in a binary search tree summing to a target value

前端 未结 3 972
梦谈多话
梦谈多话 2021-01-30 05:28

Given a binary search tree and a target value, find all the paths (if there exists more than one) which sum up to the target value. It can be any path in the tree. It doesn\'t h

3条回答
  •  暖寄归人
    2021-01-30 06:13

    Old question, but here's my stab at it - should be O(n) time as your visiting each node only once:

      public static List> pathSum(Node head, int sum) {
        List currentPath = new ArrayList();
        List> validPaths = new ArrayList>();
    
        dfsSum(head, sum, currentPath, validPaths);
    
        return validPaths;
      }
    
      public static void dfsSum(Node head, int sum, List currentPath, List> validPaths) {
        if (head == null) return;
    
        currentPath.add(head.val);
    
        if (head.left == null && head.right == null && sum == head.val) {
          validPaths.add(new ArrayList(currentPath));
        }
    
        dfsSum(head.left, sum - head.val, new ArrayList(currentPath), validPaths);
        dfsSum(head.right, sum - head.val, new ArrayList(currentPath), validPaths);
      }
    

    And the node class:

    class Node {
        public int val;
        public Node left;
        public Node right;
    
        public Node(int val) {
          this.val = val;
        }
      }
    

提交回复
热议问题