Amazon Interview Question
SDE1sCountry: India
Interview Type: Written Test
Traverse the tree in postorder and pass on the sums from child nodes to its parent.
Code:
public int getSumOfChildNodes(BinaryTree root) {
if (root == null)
return 0;
int left = getSumOfChildNodes(root.left);
int right = getSumOfChildNodes(root.right);
int sum = left + right + root.data;
System.out.println(root.data + " " + sum);
return sum;
}
void createSumTree(struct node *root){
if(root==NULL || ( root->left==NULL && root->right==NULL)){
return;
}
else{
int ls = 0;
int rs = 0;
createSumTree(root->left);
createSumTree(root->right);
if(root->left){
ls = root->left->data;
}
if(root->right){
rs = root->right->data;
}
root->data = ls + rs + root->data;
}
}
typedef struct bst {
int data;
bstptr left;
bstptr right;
}* bstptr;
int treesum(bstptr b) {
if(!b)
return 0;
return b.data + treesum(b->left) + treesum(b->right);
}
public class TreeSumNodes {
/**
* @param args
*/
public static void main(String[] args) {
TreeNode head = new TreeNode(1);
head.leftchild = new TreeNode(2);
head.rightchild = new TreeNode(3);
head.leftchild.leftchild = new TreeNode(4);
head.leftchild.rightchild = new TreeNode(5);
head.rightchild.leftchild = new TreeNode(6);
head.rightchild.rightchild = new TreeNode(7);
int sum = sumOfNodePlusChildNodes(head);
System.out.println(sum);
}
private static int sumOfNodePlusChildNodes(TreeNode head) {
if (head == null) {
return 0;
}
return head.data + sumOfNodePlusChildNodes(head.leftchild) + sumOfNodePlusChildNodes(head.rightchild);
}
public static class TreeNode {
TreeNode leftchild;
TreeNode rightchild;
int data;
public TreeNode(int data) {
this.data = data;
}
}
}
public static int sumNodesBinaryTree(BTNode currNode) {
if(currNode== null) return 0;
else if(currNode.left == null and currNode.right == null)
return currNode.value;
else {
leftChildSum = sumNodesBinaryTree(currNode.left);
rightChildSum = sumNodesBinaryTree(currNode.right);
currNode.value += leftChildSum + rightChildSum ;
return currNode.value ;
}
}
Correct one:
typedef struct bst {
int data;
bstptr left;
bstptr right;
}* bstptr;
int tree_sum_tree(bstptr b) {
if(!b)
return 0;
b->data = b->data + tree_sum_tree(b->left) + tree_sum_tree(b->right);
return b->data;
}
Hi,
Here is a simpler and most elegant implementation of the algorithm in Java.
}
- Vijay Muvva April 27, 2013