计算二叉树中的所有 k-sum 路径
给定一棵二叉树和一个整数k 。任务是计算树中节点总和等于k的路径数。
一条路径可以从任何节点开始,在任何节点结束,并且只能向下,即它们不必是根节点和叶节点,树中也可以有负数。
例子:
Input : k = 5
Root of below binary tree:
1
/ \
3 -1
/ \ / \
2 1 4 5
/ / \ \
1 1 2 6
Output : No of paths with sum equals to 5 are: 8
3 2
3 1 1
1 3 1
4 1
1 -1 4 1
-1 4 2
5
1 -1 5
Input : k = 3
1
/ \
2 -1
/ \ /
1 2 3
/ \
2 5
Output : No of paths with sum equals to 3 are : 4
方法 :
在这篇文章中已经使用向量讨论了路径和等于 k 的打印路径的实现。但是,如果我们只想存储此类路径的计数,则存储在向量中并递归移动会增加空间和时间复杂度
使用回溯和无序映射可以有效地实现上述问题。
脚步:
- 我们将使用一个无序的地图,其中将填充各种路径总和。
- 对于每个节点,我们将检查当前总和和根的值是否等于 k。如果总和等于 k,则将所需答案加一。
- 然后,我们将在 map 中添加与当前sum+root->data值相差一个常数整数 k 的所有路径总和。
- 然后我们将在地图中插入当前的 sum + root->data值。
- 我们将递归检查当前根的左右子树
- 在也遍历了右子树之后,我们将从映射中删除当前 sum + root->data值,以便在进一步遍历除当前根节点之外的其他节点时不考虑它
下面是上述方法的实现:
C++
// C++ program to count the number
// of paths with sum equals to k
#include
using namespace std;
// Binary tree node
struct Node {
int data;
Node *left, *right;
Node(int x)
{
data = x;
left = right = NULL;
}
};
// Function to backtrack the tree path and
// add each path sum in the unordered map
void k_paths(Node* root, int k, unordered_map& p,
int sum, int &res)
{
// If root is not null
if (root)
{
// If root value and previous sum equal
// to k then increase the count
if (sum + root->data == k)
res++;
// Add those values also which differes
// by the current sum and root data by k
res += p[sum + root->data - k];
// Insert the sum + root value in the map
p[sum + root->data]++;
// Move to left and right trees
k_paths(root->left, k, p, sum + root->data, res);
k_paths(root->right, k, p, sum + root->data, res);
// remove the sum + root->data value from the
// map if they are n not required further or
// they do no sum up to k in any way
p[sum + root->data]--;
}
}
// Function to print the count
// of paths with sum equals to k
int printCount(Node* root, int k)
{
// To store the required answer
int res = 0;
// To store the sum
unordered_map p;
// Function call
k_paths(root, k, p, 0, res);
// Return the required answer
return res;
}
// Driver code
int main()
{
Node* root = new Node(1);
root->left = new Node(2);
root->left->left = new Node(1);
root->left->right = new Node(2);
root->right = new Node(-1);
root->right->left = new Node(3);
root->right->left->left = new Node(2);
root->right->left->right = new Node(5);
int k = 3;
cout << "No of paths with sum equals to " << k
<< " are : " << printCount(root, k) << "\n";
return 0;
}
Java
// Java program to print all root to leaf
// paths with there relative position
import java.util.ArrayList;
import java.util.HashMap;
class Graph{
static int res;
// tree structure
static class Node
{
int data;
Node left, right;
public Node(int data)
{
this.data = data;
this.left = this.right = null;
}
};
// Function to backtrack the tree path and
// add each path sum in the unordered map
static void k_paths(Node root, int k,
HashMap p, int sum)
{
// If root is not null
if (root != null)
{
// If root value and previous sum equal
// to k then increase the count
if (sum + root.data == k)
res++;
// Add those values also which differes
// by the current sum and root data by k
res += p.get(sum + root.data - k) == null ?
0 : p.get(sum + root.data - k);
// Insert the sum + root value in the map
if (!p.containsKey(sum + root.data))
{
p.put(sum + root.data, 0);
}
p.put(sum + root.data,
p.get(sum + root.data) + 1);
// Move to left and right trees
k_paths(root.left, k, p,
sum + root.data);
k_paths(root.right, k, p,
sum + root.data);
// Remove the sum + root.data value
// from the map if they are n not
// required further or they do no
// sum up to k in any way
p.put(sum + root.data,
p.get(sum + root.data) - 1);
}
}
// Function to print the count
// of paths with sum equals to k
static int printCount(Node root, int k)
{
// To store the sum
HashMap p = new HashMap<>();
// Function call
k_paths(root, k, p, 0);
// Return the required answer
return res;
}
// Driver code
public static void main(String[] args)
{
res = 0;
Node root = new Node(1);
root.left = new Node(2);
root.left.left = new Node(1);
root.left.right = new Node(2);
root.right = new Node(-1);
root.right.left = new Node(3);
root.right.left.left = new Node(2);
root.right.left.right = new Node(5);
int k = 3;
System.out.printf("No of paths with sum " +
"equals to %d are: %d\n", k,
printCount(root, k));
}
}
// This code is contributed by sanjeev2552
Python3
# Python program to count the number
# of paths with sum equals to k
# Binary tree node
from typing import Dict
class Node:
def __init__(self, x: int) -> None:
self.data = x
self.left = None
self.right = None
res = 0
# Function to backtrack the tree path and
# add each path sum in the unordered map
def k_paths(root: Node, k: int, p: Dict, sum: int) -> None:
global res
# If root is not null
if (root):
# If root value and previous sum equal
# to k then increase the count
if (sum + root.data == k):
res += 1
# Add those values also which differes
# by the current sum and root data by k
val = sum + root.data - k
if val in p:
res += p[val]
else:
res += 0
# Insert the sum + root value in the map
if (sum + root.data) not in p:
p[sum + root.data] = 0
p[sum + root.data] += 1
# Move to left and right trees
k_paths(root.left, k, p, sum + root.data)
k_paths(root.right, k, p, sum + root.data)
# remove the sum + root.data value from the
# map if they are n not required further or
# they do no sum up to k in any way
p[sum + root.data] -= 1
# Function to print the count
# of paths with sum equals to k
def printCount(root: Node, k: int) -> int:
# To store the required answer
global res
# To store the sum
p = dict()
# Function call
k_paths(root, k, p, 0)
# return res
# Driver code
if __name__ == "__main__":
root = Node(1)
root.left = Node(2)
root.left.left = Node(1)
root.left.right = Node(2)
root.right = Node(-1)
root.right.left = Node(3)
root.right.left.left = Node(2)
root.right.left.right = Node(5)
k = 3
printCount(root, k)
print("No of paths with sum equals to {} are : {}".format(k, res))
# This code is contributed by sanjeev2552
Javascript
输出:
No of paths with sum equals to 3 are : 4