← Home

226. Invert Binary Tree

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
two pointersC++Markdown
226

The trick here is to name the state correctly, then let the implementation follow. For 226. Invert Binary Tree, the solution in this repository is mainly a two pointers solution.

Guide

What?

Before optimizing anything, pin down what information is still useful after each move. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: two pointers, sliding window.

Guide

When?

Use this approach when the hard part is not syntax, but deciding what must stay true after every update. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are invertTree.

Guide

Why?

The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.

  • The queue gives the solution a level-by-level or frontier-style traversal.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Runtime: 0 ms, faster than 100.00% of C++ online submissions for Invert Binary Tree.
02//Memory Usage: 8.3 MB, less than 100.00% of C++ online submissions for Invert Binary Tree.
03/**
04 * Definition for a binary tree node.
05 * struct TreeNode {
06 *     int val;
07 *     TreeNode *left;
08 *     TreeNode *right;
09 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
10 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
11 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
12 * };
13 */
14class Solution {
15public:
16    TreeNode* invertTree(TreeNode* root) {
17        if(root != nullptr){
18            swap(root->left, root->right);
19            root->left = invertTree(root->left);
20            root->right = invertTree(root->right);
21        }
22        return root;
23    }
24};
25
26//iterative, bfs
27//Runtime: 4 ms, faster than 39.78% of C++ online submissions for Invert Binary Tree.
28//Memory Usage: 8.6 MB, less than 100.00% of C++ online submissions for Invert Binary Tree.
29/**
30 * Definition for a binary tree node.
31 * struct TreeNode {
32 *     int val;
33 *     TreeNode *left;
34 *     TreeNode *right;
35 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
36 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
37 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
38 * };
39 */
40class Solution {
41public:
42    TreeNode* invertTree(TreeNode* root) {
43        queue<TreeNode*> q;
44        q.push(root);
45        while(!q.empty()){
46            TreeNode* cur = q.front(); q.pop();
47            if(cur == nullptr) continue;
48            swap(cur->left, cur->right);
49            q.push(cur->left);
50            q.push(cur->right);
51        }
52        return root;
53    }
54};
55
56//iterative, bfs, check node before pushing into queue
57//Runtime: 0 ms, faster than 100.00% of C++ online submissions for Invert Binary Tree.
58//Memory Usage: 8.5 MB, less than 100.00% of C++ online submissions for Invert Binary Tree.
59/**
60 * Definition for a binary tree node.
61 * struct TreeNode {
62 *     int val;
63 *     TreeNode *left;
64 *     TreeNode *right;
65 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
66 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
67 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
68 * };
69 */
70class Solution {
71public:
72    TreeNode* invertTree(TreeNode* root) {
73        if(root == nullptr) return root;
74        queue<TreeNode*> q;
75        q.push(root);
76        while(!q.empty()){
77            TreeNode* cur = q.front(); q.pop();
78            swap(cur->left, cur->right);
79            if(cur->left != nullptr) q.push(cur->left);
80            if(cur->right != nullptr) q.push(cur->right);
81        }
82        return root;
83    }
84};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.