EAI Technologies Interview Question

Sum of all nodes in a binary tree.

Interview Answer

Anonymous

Sep 16, 2016

// Traverse the tree and adding up each node value , any traversal technique work public class NodeSum { public static int sumNode(TreeNode node){ //if the node is empty if(node == null){ return 0; } int sum = 0; //Stack of the TreeNode Stack<div>stack = new Stack<div>(); stack.push(node); while(!stack.empty()){ TreeNode treeNode = stack.pop(); sum = sum + treeNode.val; if(treeNode.right!=null){ stack.push(treeNode.right); } if(treeNode.left!=null){ stack.push(treeNode.left); } } return sum; }</div></div>

1