In: Computer Science
import java.util.Stack;
import java.util.ArrayList;
import java.util.Scanner;
class TreeNode{
int data;
ArrayList<TreeNode> children = new ArrayList<>();
TreeNode parent = null;
public TreeNode(int d){
data = d;
}
public TreeNode addChild(int d){
TreeNode n = new TreeNode(d);
n.setParent(this);
children.add(n);
return n;
}
public ArrayList<TreeNode> getChildren(){
return children;
}
public void setParent(TreeNode p){
parent = p;
}
public TreeNode getParent(){
return parent;
}
}
class Main {
public static void main(String[] args)
{
Scanner scan = new
Scanner(System.in);
int num;
//Create a tree
TreeNode root = new
TreeNode(scan.nextInt());
TreeNode node1 = root.addChild(scan.nextInt());
TreeNode node11 = node1.addChild(scan.nextInt());
TreeNode node12 = node1.addChild(scan.nextInt());
TreeNode node2 = root.addChild(scan.nextInt());
TreeNode node21 = node2.addChild(scan.nextInt());
TreeNode node22 = node2.addChild(scan.nextInt());
TreeNode node211 =
node21.addChild(scan.nextInt());
System.out.println(""+sum(root));
}
public static int sum(TreeNode n) {
//TODO: Find the sum of the
elements in the tree rooted in n
//Example: if the elements in the
tree are: 10, 20, 30, 40, 50, the method should return: 150
}
}
Code:
import java.util.*;
import java.util.ArrayList;
import java.util.Scanner;
class TreeNode{
int data;
ArrayList<TreeNode> children = new ArrayList<>();
TreeNode parent = null;
public TreeNode(int d){
data = d;
}
public TreeNode addChild(int d){
TreeNode n = new TreeNode(d);
n.setParent(this);
children.add(n);
return n;
}
public ArrayList<TreeNode> getChildren(){
return children;
}
public void setParent(TreeNode p){
parent = p;
}
public TreeNode getParent(){
return parent;
}
}
class Main {
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int num;
//Create a tree
TreeNode root = new TreeNode(scan.nextInt());
TreeNode node1 = root.addChild(scan.nextInt());
TreeNode node11 = node1.addChild(scan.nextInt());
TreeNode node12 = node1.addChild(scan.nextInt());
TreeNode node2 = root.addChild(scan.nextInt());
TreeNode node21 = node2.addChild(scan.nextInt());
TreeNode node22 = node2.addChild(scan.nextInt());
TreeNode node211 = node21.addChild(scan.nextInt());
System.out.println(""+sum(root));
}
public static int sum(TreeNode n) {
int su = 0;
if(n==null)
return 0;
Queue<TreeNode> q = new LinkedList<>();
q.add(n);
while (!q.isEmpty())
{
int ni = q.size();
// If this node has children
while (ni > 0)
{
// Dequeue an item from queue and
// add it to variable "sum"
TreeNode p = q.peek();
q.remove();
su += p.data;
// Enqueue all children of the dequeued item
for (int i = 0; i < p.children.size(); i++)
q.add(p.children.get(i));
ni--;
}
}
return su;
}
}
Output: