Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create Diagonal sum in BST.java #95

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 76 additions & 0 deletions Searching/Diagonal sum in BST.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
//Find the diagonal sum of a binary tree
import java.util.HashMap;
import java.util.Map;

// A class to store a binary tree node
class Node
{
int data;
Node left = null, right = null;

Node(int data) {
this.data = data;
}
}

class Main
{
// Recursive function to perform preorder traversal on the tree and
// fill the map with the diagonal sum of elements
public static void diagonalSum(Node root, int diagonal, Map<Integer, Integer> map)
{
// base case: empty tree
if (root == null) {
return;
}

// update the current diagonal with the node's value
map.put(diagonal, map.getOrDefault(diagonal, 0) + root.data);

// recur for the left subtree by increasing diagonal by 1
diagonalSum(root.left, diagonal + 1, map);

// recur for the right subtree with the same diagonal
diagonalSum(root.right, diagonal, map);
}

// Function to print the diagonal sum of a given binary tree
public static void diagonalSum(Node root)
{
// create an empty map to store the diagonal sum for every slope
Map<Integer, Integer> map = new HashMap<>();

// traverse the tree in a preorder fashion and fill the map
diagonalSum(root, 0, map);

// traverse the map and print the diagonal sum
System.out.println(map.values());
}

public static void main(String[] args)
{
/* Construct the following tree
1
/ \
/ \
2 3
/ / \
/ / \
4 5 6
/ \
/ \
7 8
*/

Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.right.left = new Node(5);
root.right.right = new Node(6);
root.right.left.left = new Node(7);
root.right.left.right = new Node(8);

diagonalSum(root);
}
}