// C# code to implement above approach
using System;
using System.Collections.Generic;
public class GFG {
// Structure of a tree node
class Node {
public int data;
public Node left;
public Node right;
public Node(int val)
{
this.data = val;
this.left = null;
this.right = null;
}
}
// Function for marking the parent node
// for all the nodes using DFS
static void dfs(Node root, Dictionary<Node, Node> par)
{
if (root == null)
return;
if (root.left != null)
par.Add(root.left, root);
if (root.right != null)
par.Add(root.right, root);
dfs(root.left, par);
dfs(root.right, par);
}
static int sum;
// Function calling for finding the sum
static void dfs3(Node root, int h, int k,
Dictionary<Node, int> vis,
Dictionary<Node, Node> par)
{
if (h == k + 1)
return;
if (root == null)
return;
if (vis.ContainsKey(root))
return;
sum += root.data;
vis.Add(root, 1);
dfs3(root.left, h + 1, k, vis, par);
dfs3(root.right, h + 1, k, vis, par);
dfs3(par[root], h + 1, k, vis, par);
}
// Function for finding
// the target node in the tree
static Node dfs2(Node root, int target)
{
if (root == null)
return null;
if (root.data == target)
return root;
Node node1 = dfs2(root.left, target);
Node node2 = dfs2(root.right, target);
if (node1 != null)
return node1;
if (node2 != null)
return node2;
return null;
}
static int sum_at_distK(Node root, int target, int k)
{
// Hash Map to store
// the parent of a node
Dictionary<Node, Node> par
= new Dictionary<Node, Node>();
// Make the parent of root node as NULL
// since it does not have any parent
par.Add(root, null);
// Mark the parent node for all the
// nodes using DFS
dfs(root, par);
// Find the target node in the tree
Node node = dfs2(root, target);
// Hash Map to mark
// the visited nodes
Dictionary<Node, int> vis
= new Dictionary<Node, int>();
sum = 0;
// DFS call to find the sum
dfs3(node, 0, k, vis, par);
return sum;
}
static public void Main()
{
// Code
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(9);
root.left.left = new Node(4);
root.right.left = new Node(5);
root.right.right = new Node(7);
root.left.left.left = new Node(8);
root.left.left.right = new Node(19);
root.right.right.left = new Node(20);
root.right.right.right = new Node(11);
root.left.left.left.left = new Node(30);
root.left.left.right.left = new Node(40);
root.left.left.right.right = new Node(50);
int target = 9, K = 1;
// Function call
Console.Write(sum_at_distK(root, target, K));
}
}
// This code is contributed by lokesh(lokeshmvs21).