Binary Tree
Binary Tree
void BFS()
{
Node* node = root;
int h = height(node);
for (int i = 1; i <= h; i++)
{
printCurrentLevel(node, i);
}
}
Q2
void longestPathSum(BTNode* node, int sum, int len, int& maxLen, int& maxSum)
{
if (node == nullptr)
{
if (maxLen < len)
{
maxLen = len;
maxSum = sum;
}
else if (maxLen == len && maxSum < sum)
{
maxSum = sum;
}
return;
}
longestPathSum(node->left, sum + node->val, len + 1, maxLen, maxSum);
longestPathSum(node->right, sum + node->val, len + 1, maxLen, maxSum);
}
Q3
BTNode* lowestCommonAncestor(BTNode* root, int a, int b)
{
if (root == nullptr || root->val == a || root->val == b)
{
return root;
}
if (left != nullptr)
{
return left;
}
return right;
}
Q4
int sumDigitPath(BTNode* node, int currentSum)
{
if (node == nullptr)
{
return 0;
}
int sum = 0;
if (node->left != nullptr)
{
sum = (sum + sumDigitPath(node->left, currentSum)) % 27022001;
}
if (node->right != nullptr)
{
sum = (sum + sumDigitPath(node->right, currentSum)) % 27022001;
}
return sum;
}
Q5
int countTwoChildrenNode(Node* node)
{
if (node == nullptr)
{
return 0;
}
int count = 0;
if (node->pLeft != nullptr && node->pRight != nullptr)
{
count = 1;
}
int leftCount = countTwoChildrenNode(node->pLeft);
int rightCount = countTwoChildrenNode(node->pRight);
return count + leftCount + rightCount;
}
int countTwoChildrenNode()
{
return countTwoChildrenNode(root);
}
Q6
int getHeight(Node* node)
{
if (node == nullptr)
{
return 0;
}
int leftHeight = getHeight(node->pLeft);
int rightHeight = getHeight(node->pRight);
if (leftHeight >= rightHeight)
{
return leftHeight + 1;
}
else
{
return rightHeight + 1;
}
}
int getHeight()
{
return getHeight(root);
}
string preOrder()
{
string s = "";
preOrder(root);
return s;
}
string inOrder()
{
string s = "";
inOrder(root);
return s;
}
string postOrder()
{
string s = "";
postOrder(root);
return s;
}
Q7
int sumOfLeafs(Node* node)
{
if (node == nullptr)
{
return 0;
}
int sumOfLeafs()
{
return sumOfLeafs(root);
}