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();
}

Find the max sum between any two leaves
int maxLeavesSum(Node root, ref int leavesSum)
{
if (root == null) { leavesSum = 0; return;}
if (root.left == null && root.right == null){ leavesSum = root.data; return root.data;}
int ls = maxLeavesSum(root.left, ref leavesSum);
int rs = maxLeavesSum(root.right, ref leavesSum);
if (root.left && root.right)
{
leavesSum = max(leavesSum, rs+ls+root.data);
return max(ls,rs)+root.data;
}
return (!root.left) ? rs + root.data : ls + root.data;
}

No comments:

Post a Comment