打印二叉树中从根到叶的所有路径,并指定总和
- 最后更新 : 2021年8月9日
给定一个二叉树,目标总和为K,任务是打印从根到叶的所有可能路径,这些路径的总和等于K。
举例说明。
Input:
方法。我 们的想法是使用二叉树的递归进行DFS遍历,并使用一个堆栈。按照下面的步骤来实现这个方法。
- 将当前节点的值推入堆栈。
- 如果当前节点是一个叶子节点。检查叶子节点的数据是否等于剩余的target_sum。
a.如果等于就把值推到堆栈中,并把整个堆栈添加到我们的答案列表中。
**b.**否则我们就不需要这个根到叶的路径。 - 通过从target_sum中减去当前节点的值,递归地调用左子树和右子树。
- 从堆栈中弹出最上面的元素,因为我们已经对这个节点进行了操作。
下面是上述方法的实现。
Java
// Java program for the above approachimport java.util.*;class GFG {static List<List<Integer> > result=new ArrayList<>();// structure of a binary tree.static class Node {int data;Node left, right;};// Function to create new nodestatic Node newNode(int data){Node temp =new Node();temp.data = data;temp.left = temp.right =null;return temp;}// util function that// updates the stackstatic void pathSumUtil(Node node,int targetSum,Stack<Integer> stack){if (node ==null) {return;}stack.push(node.data);if (node.left ==null&& node.right ==null) {if (node.data == targetSum) {result.add(new ArrayList<>(stack));}}pathSumUtil(node.left,targetSum - node.data,stack);pathSumUtil(node.right,targetSum - node.data,stack);stack.pop();}// Function returning the list// of all valid pathsstatic List<List<Integer> > pathSum(Node root,int targetSum){if (root ==null) {return result;}Stack<Integer> stack =new Stack<>();pathSumUtil(root, targetSum, stack);return result;}// Driver codepublic static void main(String[] args){Node root = newNode(5);root.left = newNode(4);root.right = newNode(8);root.left.left = newNode(11);root.right.left = newNode(13);root.right.right = newNode(4);root.left.left.left = newNode(7);root.left.left.right = newNode(2);root.right.right.left = newNode(5);root.right.right.right = newNode(1);/*Tree:5/ \4 8/ / \11 13 4/ \ / \7 2 5 1*/// Target sum as Kint K =22;// Calling the function// to find all valid pathsList<List<Integer> > result= pathSum(root, K);// Printing the pathsif (result.isEmpty())System.out.println("NA");elsefor (List l : result) {System.out.println(l);}}} |
输出
[5, 4, 11, 2]
[5, 8, 4, 5]
时间复杂度。 O(N)
辅助空间。O (N)。
读者请注意!现在不要停止学习。以学生可接受的价格获得所有重要的DSA概念。 DSA自学课程以适合学生的价格掌握所有重要的DSA概念,并为行业做好准备。 要完成从学习语言到DS Algo以及更多的准备工作,请参考 完整的面试准备课程.
如果你想参加专家的现场课程 ,请参考 面向在职人士的DSA现场课程 和 面向学生的竞争性编程直播课程.
我的个人笔记 arrow_drop_up
保存