700681. Exchange the Leaf Nodes

Easy

Exchange the Leaf Nodes

Slug: exchange-the-leaf-nodes

Difficulty: Easy

Topic Tags: Tree, Data Structures

Company Tags: None

Summary

This problem requires you to write an algorithm that exchanges the leaf nodes in a given binary tree. The key concepts involved are tree traversal and manipulation.

Detailed Explanation

The approach to solve this problem is to perform an in-order traversal of the binary tree. During the traversal, we keep track of the current node and its children. If the current node is a leaf node (i.e., it has no children), we exchange its value with the values of its children.

Here's a step-by-step breakdown of the solution:

  1. Start by initializing a stack to store nodes from the tree.
  2. Traverse the tree using an in-order traversal algorithm.
  3. For each node, if it is a leaf node (i.e., it has no children), exchange its value with the values of its children.
  4. Continue traversing the tree until all nodes have been processed.

Here's an ASCII art diagram to illustrate the process:

       1
     /   \
    2     3
   / \   / \
  4   5 6   7

In this example, the leaf nodes are 4 and 5. We would exchange their values with the values of their children (not shown in the diagram). The resulting tree would look like:

       1
     /   \
    2     3
   / \   / \
  7   6 8   9

The time complexity of this algorithm is O(n), where n is the number of nodes in the tree, because we visit each node once. The space complexity is O(h), where h is the height of the tree, because that's the maximum depth of our stack.

Optimized Solutions

Java

View on GeeksforGeeks
public class Tree {
    public static void exchangeLeafNodes(Node root) {
        if (root == null) return;
        Stack<Node> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            Node node = stack.pop();
            if (node.left == null && node.right == null) { // leaf node
                int temp = node.val;
                node.val = node.left != null ? node.left.val : 0;
                node.val += node.right != null ? node.right.val : 0;
                if (node.left != null) stack.push(node.left);
                if (node.right != null) stack.push(node.right);
            } else {
                if (node.right != null) stack.push(node.right);
                if (node.left != null) stack.push(node.left);
            }
        }
    }

    public static class Node {
        int val;
        Node left, right;

        public Node(int val) {
            this.val = val;
        }
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.