AlgoMaster Logo

Invert Binary Tree

tree=[4, 2, 7, 1, 3, 6, 9]
1public TreeNode invertTree(TreeNode root) {
2    if (root == null) {
3        return null;
4    }
5
6    Stack<TreeNode> stack = new Stack<>();
7    stack.push(root);
8
9    while (!stack.isEmpty()) {
10        TreeNode node = stack.pop();
11
12        // Swap the left and right children
13        TreeNode temp = node.left;
14        node.left = node.right;
15        node.right = temp;
16
17        // Add children to stack for further processing
18        if (node.left != null) {
19            stack.push(node.left);
20        }
21        if (node.right != null) {
22            stack.push(node.right);
23        }
24    }
25
26    return root;
27}
0 / 39
4271369Stack