Algorithm to print all paths with a given sum in a binary tree

后端 未结 18 1400
既然无缘
既然无缘 2020-12-24 07:04

The following is an interview question.

You are given a binary tree (not necessarily BST) in which each node contains a value. Design an algorithm t

18条回答
  •  南笙
    南笙 (楼主)
    2020-12-24 07:41

    Based on Christian's answer above:

    public void printSums(Node n, int sum, int currentSum, String buffer) {
         if (n == null) {
             return;
         }
         int newSum = currentSum + n.val;
         String newBuffer = buffer + " " + n.val;
         if (newSum == sum) {
             System.out.println(newBuffer);
         }
         printSums(n.left, sum, newSum, newBuffer);
         printSums(n.right, sum, newSum, newBuffer);
         printSums(n.left, sum, 0, "");
         printSums(n.right, sum, 0, "");
    } 
    
    printSums(root, targetSum, 0, "");
    

提交回复
热议问题