I need to print all the nodes that are N level above all Leaf Nodes. I tried below approach, but now I am stuck and unable to proceed. Please help. I need to code only using Java 7 and no other versions.
For example, I have this path 1 --> 2 --> 3 --> 4, so in this case assuming 4 is my leaf node, node 3 is 1 level above 4 and node 2 is 2 levels above leaf node 4 and node 1 is 3 levels above leaf node 4.
Note: Please use only Java 7.
public class NNodeBeforeLeaf {
static Node root;
static class Node {
int data;
Node left, right;
Node(int data){
this.data = data;
left=right=null;
}
}
public static boolean isLeaf(Node n){
if(n.right == null && n.left == null)
return true;
return false;
}
public static void main(String[] args) {
int level = 2; // level N
root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(8);
print(root, 0, level);
}
public static void print(Node n, int currLevel, int level){
if(n == null){
return;
}
if(!isLeaf(n)){
print(n.left, currLevel + 1, level);
print(n.right, currLevel + 1, level);
}
printNode(n, currLevel, level);
}
public static void printNode(Node n, int currLevel, int level){}
}
You have a miss in your structure to do this a Node know its child but not is parent so you need to build a structure that will give you this link : here is my proposition : i build a map that give me the parent associate to a node with method buildParentMap this function already list all the leaf in one pass to avoid a double iteration on your tree then i use this map to go up as many time as asked on each leaf i list just before here is a snippet
be carefull this code work but there is no security if your are trying to upper that root or if the same node is present in too child (but 2 Node with the same data wont be a problem)
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
public class NNodeBeforeLeaf {
static Node root;
static class Node {
int data;
Node left, right;
Node(int data) {
this.data = data;
left = right = null;
}
#Override
public String toString() {
return "Node : " + data;
}
}
public static boolean isLeaf(Node n) {
if (n.right == null && n.left == null)
return true;
return false;
}
public static void main(String[] args) {
int level = 2; // level N
root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(8);
print(root, 0, level);
int levelToUp = 1;
HashSet<Node> result = getUpper(levelToUp, root);
System.out.println(Arrays.toString(result.toArray()));
}
private static HashSet<Node> getUpper(int levelToUp, Node node) {
HashMap<Node, Node> parenttMap = new HashMap<Node, Node>();
LinkedList<Node> leafs = new LinkedList<Node>();
buildParentMap(node, parenttMap, leafs);
HashSet<Node> result = new HashSet<>();
for (Node leaf : leafs) {
result.add(getUpperLevel(leaf, levelToUp, parenttMap));
}
return result;
}
private static Node getUpperLevel(Node leaf, int i, HashMap<Node, Node> parenttMap) {
Node tmp = leaf;
while (i > 0) {
i--;
tmp = parenttMap.get(tmp);
}
return tmp;
}
private static void buildParentMap(Node root2, HashMap<Node, Node> hashMap, LinkedList<Node> leaf) {
if (root2 == null) {
return;
} else if (isLeaf(root2)) {
leaf.add(root2);
} else {
hashMap.put(root2.left, root2);
buildParentMap(root2.left, hashMap, leaf);
hashMap.put(root2.right, root2);
buildParentMap(root2.right, hashMap, leaf);
}
}
public static void print(Node n, int currLevel, int level) {
if (n == null) {
return;
}
printNode(n, currLevel, level);
if (!isLeaf(n)) {
print(n.left, currLevel + 1, level);
print(n.right, currLevel + 1, level);
}
}
public static void printNode(Node n, int currLevel, int level) {
String output = "";
for (int i = 0; i < currLevel; i++) {
output += "\t";
}
System.out.println(output + n);
}
}
PLEASE READ MY COMMENT FIRST
Since the nodes in your program store data only for the nodes below them, I couldn't really find a way of actually going up the tree ':), but I could think of this work around, basically what you can do is, each time you need to go up by n levels you can traverse down from the root to (curLevel - n) here is a sample program that does this (it prints all the nodes at a level which is n above the current level, i hope this is what you meant):
class tree{
static class Node{
int data;
Node left;
Node right;
Node(int data){
this.data = data;
left = null;
right = null;
}
}
static Node root;
public static boolean isLeaf(Node n){
if(n.left == null && n.right == null)
return true;
return false;
}
public static void goDownTillLevel(Node n, int level){
int l = level;
if(n != null){
if(level == 0) {
System.out.println(n.data);
}
else{
if(!isLeaf(n)){
goDownTillLevel(n.left, --level);
level = l; //since by the time the above function calls finished, level had been reduced to 0
goDownTillLevel(n.right, --level);
}
}
}
}
public static void nLevelsAbove(Node n, int curLevel, int level){
goDownTillLevel(root, (curLevel - level - 1));
}
public static void main(String args[]){
int curLevel = 0;
root = new Node(1);
curLevel++;
root.left = new Node(2);
root.right = new Node(2);
curLevel++;
root.left.left = new Node(3);
root.left.right = new Node(3);
root.right.left = new Node(3);
Node n = new Node(3);
root.right.right = n;
curLevel++;
nLevelsAbove(n, curLevel, 1);
}
}
Though I'd like to add that if going up is one of your concerns, don't use this node structure, instead add another variable to the node, a reference to the node right above it, that way this could be made much easier and shorter.
The output of the above code is:
2
2
I think that the implementation of public static boolean isLeaf(Node n) is wrong, it should check only if right is null otherwise it is not a node, either a leaf
To get the current level of node, you can try with this code
int level = 0;
while(node.right != null) {
level++;
node = node.right;
}
System.out.println("current level node: " + level);
Your structure is not able to determine the height of the current node, except when traversing from bottom to top. In order to achieve this, you have to traverse to the leafs first.
Each recursion (bottom up now) should then return it's heights. As youre not stating if your tree is a full binary tree, a node can have multiple heights depending on his children. If the heights match the desired height, the node can be printed.
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class NNodeBeforeLeaf {
static Node root;
static class Node {
int data;
Node left, right;
Node(int data) {
this.data = data;
left = right = null;
}
}
public static boolean isLeaf(Node n) {
return n.right == null && n.left == null;
}
public static void main(String[] args) {
int level = 2; // level N
root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(8);
print(root, level);
}
public static void print(Node n, int level) {
traversAndPrint(n, level);
}
private static Set<Integer> traversAndPrint(Node n, int levelToPrint) {
if (isLeaf(n)) return Collections.singleton(0); // We are a leaf, so we have height 0
final Set<Integer> childrenHeights = new HashSet<>();
// are no leaf, so we have to get the heights of our children
if (n.right != null) childrenHeights.addAll(traversAndPrint(n.right, levelToPrint));
if (n.left != null) childrenHeights.addAll(traversAndPrint(n.left, levelToPrint));
assert !childrenHeights.isEmpty();
// And increase these heights
final Set<Integer> selfHeights = new HashSet<>();
for (Integer childrenHeigth : childrenHeights) {
final int selfHeight = childrenHeigth + 1;
selfHeights.add(selfHeight);
}
// If we have the desired height, print
if (selfHeights.contains(levelToPrint)) printNode(n);
return selfHeights; // return our heights
}
public static void printNode(Node n) {
// Do whatever you want
System.out.println(n.data);
}
}
I found another approach. I put all nodes in a list. For each level up I remove the leaf nodes in that list. A leaf node in the list is defined as a node with left=null and right=null or if they are not null left and right should not be in the list. After the level ups I print the now leaf nodes in the list.
public class NNodeBeforeLeaf {
static Node root;
static class Node {
int data;
Node left, right;
Node(int data) {
this.data = data;
left = right = null;
}
}
public static boolean isLeaf(Node n) {
if ((n.right == null) && (n.left == null)) {
return true;
}
return false;
}
public static void main(String[] args) {
int level = 2; // level N
root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(8);
printNodes(getNodesNLevelAboveLeafs(root, level));
}
public static void printNodes(List<Node> nodes) {
for (Node n : nodes) {
System.out.println(n.data);
}
}
public static List<Node> getNodesNLevelAboveLeafs(Node root, int level) {
List<Node> allNodes = listAllNodes(root);
for (int i = 0; i < level; i++) {
allNodes.removeAll(getLeafNodes(allNodes));
}
return getLeafNodes(allNodes);
}
private static List<Node> getLeafNodes(List<Node> allNodes) {
List<Node> leafs = new ArrayList<>();
for (Node n : allNodes) {
if (((n.left == null) || !allNodes.contains(n.left))
&& ((n.right == null) || !allNodes.contains(n.right))) {
leafs.add(n);
}
}
return leafs;
}
private static List<Node> listAllNodes(Node node) {
List<Node> nodes = new ArrayList<>();
nodes.add(node);
if (node.left != null) {
nodes.addAll(listAllNodes(node.left));
}
if (node.right != null) {
nodes.addAll(listAllNodes(node.right));
}
return nodes;
}
}
Related
In the spirit of How to repair a corrupted MPTT tree (nested set) in the database using SQL?, I am trying to figure out an algorithm to determine the left and right values of a Modified Preorder Tree Traversal in Java given a root Node. Does anyone have any experience converting a regular pre order traversal into the modified traversal?
I currently have this as my preorder traversal.
List<Node> preorderTraversal(Node root) {
List<Node> list = new ArrayList<>();
if(root == null) return list;
Stack<Node> stack = new Stack<>();
stack.push(root);
while(!stack.empty()) {
root = stack.pop();
list.add(root);
if(root.children != null) {
for(Node child : root.children) {
if(child != null) {
stack.push(child);
}
}
}
}
return list;
}
Firstly, your preorder traversal code traverses children in reverse order. When you push the children onto the stack in order, they get popped in reverse order, leading to incorrect behaviour. It should be something like this:
static List<Node> preorderTraversal(Node root) {
List<Node> list = new ArrayList<>();
if (root == null) return list;
Stack<Node> stack = new Stack<>();
stack.push(root);
while (!stack.empty()) {
root = stack.pop();
list.add(root);
if (root.children != null) {
// iterate in reverse
for (int i = root.children.size() - 1; i >= 0; i--) {
Node child = root.children.get(i);
if (child != null) {
stack.push(child);
}
}
}
}
return list;
}
Before we look at modified preorder traversal, it is helpful to look at how to implement preorder traversal recursively:
static List<Node> preorderTraversalRecursive(Node root) {
ArrayList<Node> outList = new ArrayList<>();
preorderTraversalRecursive(root, outList);
return outList;
}
private static void preorderTraversalRecursive(Node root, ArrayList<Node> outList) {
if (root == null) {
return;
}
outList.add(root);
if (root.children != null) {
for (Node child : root.children) {
preorderTraversalRecursive(child, outList);
}
}
}
This code simple outputs a node before traversing its children.
To make this into a modified preorder traversal, you only need to keep track of a counter that is incremented before and after every node is processed, and record it before and after the children are processed in order to get left and right values. Here, the current count is returned by the method so that it can be changed during processing of child nodes and this updated value used for their parents' right value:
static List<MPTTNode> modifiedPreorderTraversalRecursive(Node root) {
ArrayList<MPTTNode> outList = new ArrayList<>();
modifiedPreorderTraversalRecursive(root, 0, outList);
return outList;
}
private static int modifiedPreorderTraversalRecursive(Node root, int counter, ArrayList<MPTTNode> outList) {
if (root == null) {
return counter;
}
counter++;
MPTTNode mpttNode = new MPTTNode(root.data, counter, 0); // right value is unknown, leave as 0 for now
outList.add(mpttNode);
if (root.children != null) {
for (Node child : root.children) {
// modify counter
counter = modifiedPreorderTraversalRecursive(child, counter, outList);
}
}
counter++;
mpttNode.right = counter;
return counter;
}
This can also be implemented iteratively:
static List<MPTTNode> modifiedPreorderTraversal(Node root) {
List<MPTTNode> list = new ArrayList<>();
if (root == null) return list;
Stack<Node> stack = new Stack<>();
Stack<Integer> pending = new Stack<>();
stack.push(root);
int counter = 0;
while (!stack.empty()) {
root = stack.pop();
if (root == null) {
int nodeIndex = pending.pop();
counter++;
list.get(nodeIndex).right = counter;
continue;
}
counter++;
pending.push(list.size());
list.add(new MPTTNode(root.data, counter, 0)); // right value is unknown, leave as 0 for now
stack.push(null);
if (root.children != null) {
// iterate in reverse
for (int i = root.children.size() - 1; i >= 0; i--) {
Node child = root.children.get(i);
if (child != null) {
stack.push(child);
}
}
}
}
return list;
}
This works by using a pending stack to keep track of the indices of parent nodes within the output list (list). It uses null values in the stack stack to signal that all children of a node have been processed and so the right value of their parent is known.
Here's all my code, including the same example tree as is used in the linked question:
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
Node tree = new Node("Electronics",
Arrays.asList(
new Node("Televisions",
Arrays.asList(
new Node("Tube"),
new Node("LCD"),
new Node("Plasma")
)
),
new Node("Portable Electronics",
Arrays.asList(
new Node("MP3 Players", Collections.singletonList(
new Node("Flash")
)),
new Node("CD Players"),
new Node("2 Way Radios")
)
)
)
);
List<MPTTNode> list1 = Node.modifiedPreorderTraversal(tree);
List<MPTTNode> list2 = Node.modifiedPreorderTraversalRecursive(tree);
if (!list1.equals(list2)) {
throw new RuntimeException("Traversals not equal");
}
for (var node : list1) {
System.out.printf("%-30s left:%5d, right:%5d\n", node.data, node.left, node.right);
}
}
}
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class Node {
String data;
List<Node> children;
public Node(String data, List<Node> children) {
this.data = data;
this.children = children;
}
public Node(String data) {
this.data = data;
}
static List<Node> preorderTraversal(Node root) {
List<Node> list = new ArrayList<>();
if (root == null) return list;
Stack<Node> stack = new Stack<>();
stack.push(root);
while (!stack.empty()) {
root = stack.pop();
list.add(root);
if (root.children != null) {
// iterate in reverse
for (int i = root.children.size() - 1; i >= 0; i--) {
Node child = root.children.get(i);
if (child != null) {
stack.push(child);
}
}
}
}
return list;
}
static List<MPTTNode> modifiedPreorderTraversal(Node root) {
List<MPTTNode> list = new ArrayList<>();
if (root == null) return list;
Stack<Node> stack = new Stack<>();
Stack<Integer> pending = new Stack<>();
stack.push(root);
int counter = 0;
while (!stack.empty()) {
root = stack.pop();
if (root == null) {
int nodeIndex = pending.pop();
counter++;
list.get(nodeIndex).right = counter;
continue;
}
counter++;
pending.push(list.size());
list.add(new MPTTNode(root.data, counter, 0)); // right value is unknown, leave as 0 for now
stack.push(null);
if (root.children != null) {
// iterate in reverse
for (int i = root.children.size() - 1; i >= 0; i--) {
Node child = root.children.get(i);
if (child != null) {
stack.push(child);
}
}
}
}
return list;
}
static List<Node> preorderTraversalRecursive(Node root) {
ArrayList<Node> outList = new ArrayList<>();
preorderTraversalRecursive(root, outList);
return outList;
}
private static void preorderTraversalRecursive(Node root, ArrayList<Node> outList) {
if (root == null) {
return;
}
outList.add(root);
if (root.children != null) {
for (Node child : root.children) {
preorderTraversalRecursive(child, outList);
}
}
}
static List<MPTTNode> modifiedPreorderTraversalRecursive(Node root) {
ArrayList<MPTTNode> outList = new ArrayList<>();
modifiedPreorderTraversalRecursive(root, 0, outList);
return outList;
}
private static int modifiedPreorderTraversalRecursive(Node root, int counter, ArrayList<MPTTNode> outList) {
if (root == null) {
return counter;
}
counter++;
MPTTNode mpttNode = new MPTTNode(root.data, counter, 0);
outList.add(mpttNode);
if (root.children != null) {
for (Node child : root.children) {
counter = modifiedPreorderTraversalRecursive(child, counter, outList);
}
}
counter++;
mpttNode.right = counter;
return counter;
}
}
import java.util.Objects;
public class MPTTNode {
String data;
int left;
int right;
public MPTTNode(String data, int left, int right) {
this.data = data;
this.left = left;
this.right = right;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MPTTNode mpttNode = (MPTTNode) o;
return left == mpttNode.left && right == mpttNode.right && Objects.equals(data, mpttNode.data);
}
}
Output:
Electronics left: 1, right: 20
Televisions left: 2, right: 9
Tube left: 3, right: 4
LCD left: 5, right: 6
Plasma left: 7, right: 8
Portable Electronics left: 10, right: 19
MP3 Players left: 11, right: 14
Flash left: 12, right: 13
CD Players left: 15, right: 16
2 Way Radios left: 17, right: 18
hi im new to codings and i have to print my binary search tree in a 2d model but this codes only print the orders of number in order(left-root-right) such as when i insert 10, 9, 11, 8, it will print inorder (left root right) = 8,9,10,11. what method or codes should i add to create a 2d tree here. sorry idk how to properly put the codes here just look at it like it is only a one code only.
class binarySearchTree {
class Node {
int key;
Node left, right;
int data;
public Node(int data){
key = data;
left = right = null;
}
}
// BST root node
Node root;
// Constructor for BST =>initial empty tree
binarySearchTree(){
root = null;
}
//delete a node from BST
void deleteKey(int key) {
root = delete_Recursive(root, key);
}
//recursive delete function
Node delete_Recursive(Node root, int key) {
//tree is empty
if (root == null) return root;
//traverse the tree
if (key < root.key) //traverse left subtree
root.left = delete_Recursive(root.left, key);
else if (key > root.key) //traverse right subtree
root.right = delete_Recursive(root.right, key);
else {
// node contains only one child
if (root.left == null)
return root.right;
else if (root.right == null)
return root.left;
// node has two children;
//get inorder successor (min value in the right subtree)
root.key = minValue(root.right);
// Delete the inorder successor
root.right = delete_Recursive(root.right, root.key);
}
return root;
}
int minValue(Node root) {
//initially minval = root
int minval = root.key;
//find minval
while (root.left != null) {
minval = root.left.key;
root = root.left;
}
return minval;
}
// insert a node in BST
void insert(int key) {
root = insert_Recursive(root, key);
}
//recursive insert function
Node insert_Recursive(Node root, int key) {
//tree is empty
if (root == null) {
root = new Node(key);
return root;
}
//traverse the tree
if (key < root.key) //insert in the left subtree
root.left = insert_Recursive(root.left, key);
else if (key > root.key) //insert in the right subtree
root.right = insert_Recursive(root.right, key);
// return pointer
return root;
}
void inorder() {
inorder_Recursive(root);
}
// recursively traverse the BST
void inorder_Recursive(Node root) {
if (root != null) {
inorder_Recursive(root.left);
System.out.print(root.key + " x ");
inorder_Recursive(root.right);
}
}
//PostOrder Traversal - Left:Right:rootNode (LRn)
void postOrder(Node node) {
if (node == null)
return;
// first traverse left subtree recursively
postOrder(node.left);
// then traverse right subtree recursively
postOrder(node.right);
// now process root node
System.out.print(node.key + " ");
}
// InOrder Traversal - Left:rootNode:Right (LnR)
void inOrder(Node node) {
if (node == null)
return;
//first traverse left subtree recursively
inOrder(node.left);
//then go for root node
System.out.print(node.key + " ");
//next traverse right subtree recursively
inOrder(node.right);
}
//PreOrder Traversal - rootNode:Left:Right (nLR)
void preOrder(Node node) {
if (node == null)
return;
//first print root node first
System.out.print(node.key + " ");
// then traverse left subtree recursively
preOrder(node.left);
// next traverse right subtree recursively
preOrder(node.right);
}
// Wrappers for recursive functions
void postOrder_traversal() {
postOrder(root); }
void inOrder_traversal() {
inOrder(root); }
void preOrder_traversal() {
preOrder(root); }
}
here i found this codes in stackoverflow, i want te output like this, i can use this but i dont know how can i make this as user input for the data and make it insert the integer into a tree not this manually inserted of the integer. thankyou very much to whoever put effort to understand my question and my situation as newbie.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class BTreePrinterTest {
private static Node<Integer> test2() {
Node<Integer> root = new Node<Integer>(2);
Node<Integer> n11 = new Node<Integer>(3);
Node<Integer> n12 = new Node<Integer>(5);
Node<Integer> n21 = new Node<Integer>(2);
Node<Integer> n22 = new Node<Integer>(6);
Node<Integer> n23 = new Node<Integer>(9);
Node<Integer> n31 = new Node<Integer>(5);
root.left = n11;
root.right = n12;
n11.left = n21;
n11.right = n22;
n12.left = n23;
n12.right = n31;
return root;
}
public static void main(String[] args) {
BTreePrinter.printNode(test2());
}
}
class Node<T extends Comparable<?>> {
Node<T> left, right;
T data;
public Node(T data) {
this.data = data;
}
}
class BTreePrinter {
public static <T extends Comparable<?>> void printNode(Node<T> root) {
int maxLevel = BTreePrinter.maxLevel(root);
printNodeInternal(Collections.singletonList(root), 1, maxLevel);
}
private static <T extends Comparable<?>> void printNodeInternal(List<Node<T>> nodes, int level, int maxLevel) {
if (nodes.isEmpty() || BTreePrinter.isAllElementsNull(nodes))
return;
int floor = maxLevel - level;
int endgeLines = (int) Math.pow(2, (Math.max(floor - 1, 0)));
int firstSpaces = (int) Math.pow(2, (floor)) - 1;
int betweenSpaces = (int) Math.pow(2, (floor + 1)) - 1;
BTreePrinter.printWhitespaces(firstSpaces);
List<Node<T>> newNodes = new ArrayList<Node<T>>();
for (Node<T> node : nodes) {
if (node != null) {
System.out.print(node.data);
newNodes.add(node.left);
newNodes.add(node.right);
} else {
newNodes.add(null);
newNodes.add(null);
System.out.print(" ");
}
BTreePrinter.printWhitespaces(betweenSpaces);
}
System.out.println("");
for (int i = 1; i <= endgeLines; i++) {
for (int j = 0; j < nodes.size(); j++) {
BTreePrinter.printWhitespaces(firstSpaces - i);
if (nodes.get(j) == null) {
BTreePrinter.printWhitespaces(endgeLines + endgeLines + i + 1);
continue;
}
if (nodes.get(j).left != null)
System.out.print("/");
else
BTreePrinter.printWhitespaces(1);
BTreePrinter.printWhitespaces(i + i - 1);
if (nodes.get(j).right != null)
System.out.print("\\");
else
BTreePrinter.printWhitespaces(1);
BTreePrinter.printWhitespaces(endgeLines + endgeLines - i);
}
System.out.println("");
}
printNodeInternal(newNodes, level + 1, maxLevel);
}
private static void printWhitespaces(int count) {
for (int i = 0; i < count; i++)
System.out.print(" ");
}
private static <T extends Comparable<?>> int maxLevel(Node<T> node) {
if (node == null)
return 0;
return Math.max(BTreePrinter.maxLevel(node.left), BTreePrinter.maxLevel(node.right)) + 1;
}
private static <T> boolean isAllElementsNull(List<T> list) {
for (Object object : list) {
if (object != null)
return false;
}
return true;
}
}
btw im learning this by my own, i tried merging the two codes but it gives me error i cant fix it.
I should have not made the whole exercise for you, so please try to understand the code. Tell me if something is not clear for you.
public static void main(String[] args) throws IOException {
System.out.println("Write your input");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String lines = br.readLine();
binarySearchTree b = new binarySearchTree();
b.input(lines);
b.print();
}
These functions go to binarySearchTree.
protected void printRecursive(Node node, int depth) {
System.out.println("");
for(int i = 0; i<depth; i++) {
System.out.print(" ");
}
System.out.print(node.key);
if(node.left != null) {
printRecursive(node.left, depth + 1);
}
if(node.right != null) {
printRecursive(node.right, depth + 1);
}
}
public void input(String s) throws IOException {
String[] strs = s.trim().split("\\s+");
for (int i = 0; i < strs.length; i++) {
insert(Integer.parseInt(strs[i]));
}
}
Also i used this answer in my code.
Hi how do I make the program output the sum of the numbers instead of giving them out seperately?
public class Tree {
private Node root;
public int sum;
public class Node{
private Node left;
private Node right;
private int val;
public Node(int data) {
this.val = data;
}
}
public void createTree() {
Node first = new Node(7);
Node second = new Node(2);
Node third = new Node(6);
Node fourth = new Node(4);
root = first;
first.left = second;
first.right = third;
second.left = fourth;
}
public void Sum(Node root) {
if(root == null) {
return;
}
System.out.print(root.val + " ");
Sum(root.left);
Sum(root.right);
}
public static void main(String[] args) {
Tree tree = new Tree();
tree.createTree();
tree.Sum(tree.root);
}
}
Current output is 7 2 6 4 but I want them to be added into a sum in the System outprint if possible. I couldnt get it to work for some reason so maybe someone can help me with it.
You can recursively get the sum by doing the following:
public double sum(Node root) {
double leftSum, rightSum, totalSum;
if (root == null) {
totalSum = 0;
return totalSum;
}else {
leftSum = sum(root.left);
rightSum = sum(root.right);
totalSum = root.val + leftSum + rightSum;
return totalSum;
}
}
You need to return the sum of the left and right nodes and print the return value from main(). Also, there's no need for sum() to be an intance method since you're passing in root:
public static int sum(Node root) {
if(root == null) {
return 0;
}
return sum(root.left) + sum(root.right);
}
public static void main(String[] args) {
Tree tree = new Tree();
tree.createTree();
System.out.println(sum(tree.root));
}
I have referred to many posts and answers but still not able to get a working code. Below is code for sorted linked list to BST in java. Included all helper functions for linked list.
Output which I is get is not expected i.e root : 4 , root.left is 2 and root.right is 4 again. I suppose output should be root : 4 , root.left is 2 and root.right is 6
class LNode {
public int data;
public LNode next;
LNode(int newData) {
this.data = newData;
}
}
class Node {
int data;
Node left;
Node right;
public Node prev;
Node(int d) {
data = d;
left = right = null;
}
}
class LinkedList {
LNode first;
LNode head;
LNode newNode;
public LinkedList() {
first = null;
}
public void insertAtBeginning(int x) {
newNode = new LNode(x);
if (first != null) {
newNode.next = first;
first = newNode;
head = first;
} else {
first = newNode;
head = first;
}
}
public void printList()
{
head = first;
while (first != null) {
System.out.print(first.data + " --> ");
first = first.next;
}
System.out.println("null");
first = head;
}
}
public class LLtoBST {
public static Node root;
//public static LNode first;
public static Node sortedListToBST(LNode first, int end) {
return sortedListToBST(first, 0, end);
}
public static Node sortedListToBST(LNode first, int start, int end) {
if (start > end)
return null;
if (first != null) {
int mid = start + (end - start) / 2;
Node lnode = sortedListToBST(first, start, mid - 1);
root = new Node(first.data);
first = first.next;
Node rnode = sortedListToBST(first, mid + 1, end);
root.left = lnode;
root.right = rnode;
}
return root;
}
public static void main(String... args) {
LinkedList list = new LinkedList();
int n = 0;
list.insertAtBeginning(7);
list.insertAtBeginning(6);
list.insertAtBeginning(5);
list.insertAtBeginning(4);
list.insertAtBeginning(3);
list.insertAtBeginning(2);
list.insertAtBeginning(1);
list.printList();
first = list.head;
while (first != null) {
n++;
first = first.next;
}
first = list.head;
Node curr = sortedListToBST(first, n);
System.out.println(curr.data);
System.out.println(curr.left.data);
System.out.println(curr.right.data);
}
}
Output :
1 --> 2 --> 3 --> 4 --> 5 --> 6 --> 7 --> null
4
2
4
Any help would be greatly appreciated.
Please make the below changes in the function sortedListToBST(LNode first, int start, int end)
Please note that the below code prints 2 as the left child of 4 and 6 as the right child of 4. Also, I have tested the code with 2 and 6 as roots. It prints 1 as the left child of 2 and 3 as the right child of 2. Also, 5 as the left child of 6 and 7 as the right child of 6.
Please also note that you need to change your test client so that it handles the use case when the left child and/or the right child are/is null. I hope the below code is helpful.
The below algorithm works on the principle of in-order traversal of tree.
Traverse the left subtree.
Visit the root.
Traverse the right subtree.
public static Node sortedListToBST(LNode first, int start, int end) {
if (start > end)
return null;
int mid = (start + end) / 2;
Node leftNode = sortedListToBST(first, start, mid - 1);
Node root = new Node(first.data);
root.left = leftNode;
if (first.next != null) {
first.data = first.next.data;
first.next = first.next.next;
}
root.right = sortedListToBST(first, mid + 1, end);
return root;
}
You didn't specify that a balanced BST is required. If you are happy with unbalanced BST, the following works:
public static Node sortedListToUnbalancedBST(LNode lNode) {
if (lNode.next != null) {
Node node = new Node(lNode.data);
node.right = sortedListToUnbalancedBST(lNode.next);
return node;
} else {
return null;
}
}
Hi guys the question is convert bst to sorted singly linked list in java
class SortedLL {
LinkedListNode<Integer> head;
LinkedListNode<Integer> tail;
}
public class Solution {
public static SortedLL sortedLL(BinaryTreeNode<Integer> root) {
if (root == null) {
SortedLL output = new SortedLL();
output.head = null;
output.tail = null;
return output;
}
SortedLL l = sortedLL(root.left);
SortedLL r = sortedLL(root.right);
LinkedListNode<Integer> n = new LinkedListNode<Integer>(root.data);
if (l.tail != null) {
l.tail.next = n;
}
if (r.head != null) {
n.next = r.head;
}
SortedLL b = new SortedLL();
if (l.head != null) {
b.head = l.head;
} else {
b.head = n;
}
if (r.tail != null) {
b.tail = r.tail;
} else {
b.tail = n;
}
return b;
}
public static LinkedListNode<Integer> BSTToSortedLL(BinaryTreeNode<Integer> root) {
return sortedLL(root).head;
}
}
I need to build a balanced binary search tree. So far my program inserts the numbers from 1 to 26, but my program does not build it into a balanced binary search tree. If anyone could look at my code and help me out it would be much appreciated.
public class TreeNode {
TreeNode leftTreeNode, rightTreeNode;// the nodes
int data;
//int size;
public TreeNode(){//Constructer
leftTreeNode = null;
rightTreeNode = null;
}
public TreeNode(int newData){//Constructer with new Data coming in for comparison
leftTreeNode = null;
rightTreeNode = null;
data = newData;
}
public TreeNode getLeft(){
return leftTreeNode;
}
public TreeNode getRight(){
return rightTreeNode;
}
public void setLeft(TreeNode leftTreeNode){
this.leftTreeNode = leftTreeNode;
}
public void setRight(TreeNode rightTreeNode){
this.rightTreeNode = rightTreeNode;
}
public int getData(){
return data;
}
// public boolean isEmpty(){//Checking to see if the the root is empty
// if(size == 0) return true;
// else return false;
public void print(){
System.out.println("Data is: " + getData());
}
}
// public void traverse (Node root){ // Each child of a tree is a root of its subtree.
// if (root.getLeft() != null){
// traverse (root.getLeft());
// }
// System.out.println(root.data);
// if (root.getRight() != null){
// traverse (root.getRight());
// }
//}
public class BinarySearchTree {
TreeNode root;
public BinarySearchTree(){
root = null;
}
public TreeNode getRoot(){
return root;
}
public void insert(int data) { //Insert method checking to see where to put the nodes
TreeNode node1 = new TreeNode(data);
if (root == null) {
root = node1;
}
else{
TreeNode parIns = root;//Parent
TreeNode insNode = root;//Insertion Node
while(insNode != null){
parIns = insNode;
if(data < insNode.getData()){//If the data is less than the data coming in place it on the left
insNode = insNode.getLeft();
}else{//Place it on the right
insNode = insNode.getRight();
}
}//Searching where to put the node
if(data < parIns.getData()){
parIns.setLeft(node1);
}else{
parIns.setRight(node1);
}
}
}
public void printInorder(TreeNode n){
if(n != null){
printInorder(n.getLeft());//L
n.print();//N
printInorder(n.getRight());//R
}
}
// public TreeNode balance(tree, int start, int end){
// if(start > end) return null;
// int mid = (start + end) /2;
// TreeNode node;
// TreeNode leftChild;
// TreeNode rightChild;
//
// if(node <= mid){
// leftChild = balance(arr[mid -1], start, end);/*Make the left child if the node coming in is
// less than the mid node */
//
//
// }else{
// rightChild = balance(arr[mid]+1, start, end);/*Make the rigth child if the node is
// greater than the mid node*/
//
// }
// return node;
// }
public static void main(String[] args) {
BinarySearchTree tree = new BinarySearchTree();
tree.insert(1);
tree.insert(2);
tree.insert(3);
tree.insert(4);
tree.insert(5);
tree.insert(6);
tree.insert(7);
tree.insert(8);
tree.insert(9);
tree.insert(10);
tree.insert(11);
tree.insert(12);
tree.insert(13);
tree.insert(14);
tree.insert(15);
tree.insert(16);
tree.insert(17);
tree.insert(18);
tree.insert(19);
tree.insert(20);
tree.insert(21);
tree.insert(22);
tree.insert(23);
tree.insert(24);
tree.insert(25);
tree.insert(26);
tree.printInorder(tree.getRoot());
}
}
//for(int i = 1; i <= 26; i++)
//tree.insert(i);
public void balance(TreeNode tree, int start, int end){
TreeNode tree1 = new TreeNode(data);
if(start <= end){
int mid = (start + end) /2;
//TreeNode node;
TreeNode leftChild;
TreeNode rightChild;
if(tree1.getData() <= mid){
leftChild = balance(tree1(mid -1), start, end);/*Make the left child if the node coming in is
less than the mid node */
}else{
rightChild = balance(tree1(mid+1), start, end);/*Make the rigth child if the node is
greater than the mid node*/
}
}
}
How can I fix the balance function to properly balance my tree?
Since your tree does not self-balance, whether or not it's balanced will depend on the order of insertion of the elements.
If you want your tree to be balanced regardless, you will need to take care of the balancing in your class. For example, take a look at the Red-Black Tree data structure.
public class BinarySearchTree {
TreeNode root;
public BinarySearchTree(){
root = new TreeNode();
}
public TreeNode getRoot(){
return root;
}
public void insert(int data) {
root = insert(root, data);
}//Insert method checking to see where to put the nodes
// public void insert(TreeNode node, int data){
// TreeNode node1 = new TreeNode(data);
// if (root == null) {
// root = node1;
// }
// else{
// TreeNode parIns = root;//Parent
// TreeNode insNode = root;//Insertion Node
//
// while(insNode != null){
// parIns = insNode;
//
// if(data < insNode.getData()){//If the data is less than the data coming in place it on the left
// insNode = insNode.getLeft();
// }else{//Place it on the right
// insNode = insNode.getRight();
// }
// }//Searching where to put the node
//
// if(data < parIns.getData()){
// parIns.setLeft(node1);
// }else{
// parIns.setRight(node1);
// }
//
// }
// }
private TreeNode insert(TreeNode node, int data) {
if(root.data == 0)
root.data = data;
else if (node==null) {
node = new TreeNode(data);
}
else {
if (data <= node.data) {
node.leftTreeNode = insert(node.leftTreeNode, data);
}
else {
node.rightTreeNode = insert(node.rightTreeNode, data);
}
}
return(node); // in any case, return the new pointer to the caller
}
public void printPreOrder(){
printPreOrder(root);
}
public void printPreOrder(TreeNode n){
if(n != null){
n.print();//N
printPreOrder(n.getLeft());//L
printPreOrder(n.getRight());//R
}
}
public TreeNode balance(int[] a, int start, int end){
TreeNode node = new TreeNode();
if(start <= end){
int mid = start + (end - start) /2;
node.data = a[mid];
if(root.data == 0)
root = node;
node.leftTreeNode = balance(a, start, mid -1);/*Make the left child if the node coming in is
less than the mid node */
node.rightTreeNode = balance(a, mid + 1, end);/*Make the rigth child if the node is
greater than the mid node*/
}
else{
return null;
}
return node;
}
public static void main(String[] args) {
BinarySearchTree tree = new BinarySearchTree();
//int[] a = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,21,22,23,24,25,26};
int[] a = new int[26];
for(int i = 0; i < 26; i++){
a[i] = i + 1;
}
for(int i = 1; i <= 26; i++)
tree.insert(i);
tree.printPreOrder();
BinarySearchTree tree2 = new BinarySearchTree();
tree2.balance(a, 0, 25);
System.out.println("Now I am going to balance my tree");
tree2.printPreOrder();
}
}
public class TreeNode {
TreeNode leftTreeNode, rightTreeNode;// the nodes
int data;
//int size;
public TreeNode(){//Constructer
leftTreeNode = null;
rightTreeNode = null;
data = 0;
}
public TreeNode(int newData){//Constructer with new Data coming in for comparison
leftTreeNode = null;
rightTreeNode = null;
data = newData;
}
public TreeNode getLeft(){
return leftTreeNode;
}
public TreeNode getRight(){
return rightTreeNode;
}
public void setLeft(TreeNode leftTreeNode){
this.leftTreeNode = leftTreeNode;
}
public void setRight(TreeNode rightTreeNode){
this.rightTreeNode = rightTreeNode;
}
public int getData(){
return data;
}
// public boolean isEmpty(){//Checking to see if the the root is empty
// if(size == 0) return true;
// else return false;
public void print(){
System.out.println("Data is: " + getData());
}
}