Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Recursive Strategies for Binary Tree Manipulation and Summation

Tech May 16 1

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.

Tags: Recursion

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.