Sunday, June 26, 2016

#codingexercise
Given a BinaryTree and a value, check if the path sum from root to leaf equals the given value.
bool hasPathSum(Node root, int sum)
{
if (root ==null) return sum == 0;
int newsum = sum-root.data;
if (newsum == 0 && root.left == null && root.right == null) return true;
return hasPathSum(root.left, newsum) || hasPathSum(root.right, newsum);
}
Find the maximum sum from root to leaf in a binary tree
void maxPathSum(Node root, ref int sum, ref int max)
{
if (root == null) { if (sum > max) max = sum; return;}
sum += root.data;
maxPath(root.left, ref sum, ref max);
maxPath(root.right, ref sum, ref max);
sum-= root.data;
}
Print all root to leaf paths
void getAllPaths(Node root, ref List<Node> candidate, ref List<List<Node>> paths )
{
if (root == null) { paths.Add(candidate); return;}
candidate.add(root);
getAllPaths(root.left, ref candidate, ref paths);
getAllPaths(root.right, ref candidate, ref paths);
candidate.removeLast();
}

No comments:

Post a Comment