Recursive Strategies for Binary Tree Manipulation and Summation
Inverting a Binary Tree
To invert a binary tree, swap the left and right children of every node recursively. The core idea is: for each node, first swap its children, then recursively apply the same operation to both subtrees.
The base case occurs when the current node is nullptr, in which case no action is needed.
TreeNode* invertTree(TreeNode* root) {
if (!root) return root;
std::swap(root->left, root->right);
invertTree(root->left);
invertTree(root->right);
return root;
}
This approach uses a pre-order traversal pattern—processing the current node (swapping) before recursing into children.
Sum of Left Leaves
A left leaf is defined as a leaf node that is the left child of its parent. To compute the sum of all such nodes:
- Recursively process both left and right subtrees.
- When visiting a node, check if its left child exists and is a leaf (i.e., has no children). If so, include its value in the sum.
- The recursion terminates when a node is
nullptr.
Note that a standalone leaf (the root with no children) does not count as a left leaf.
int sumOfLeftLeaves(TreeNode* root) {
if (!root) return 0;
int total = 0;
// Check if left child is a leaf
if (root->left && !root->left->left && !root->left->right) {
total += root->left->val;
}
// Recurse on both subtrees
total += sumOfLeftLeaves(root->left);
total += sumOfLeftLeaves(root->right);
return total;
}
This implemnetation avoids redundant base cases by handling the leaf check during traversal rather than relying solely on terminal conditions.