跳至主要内容

226. Invert Binary Tree

Recursion

/*
* @lc app=leetcode id=226 lang=cpp
*
* [226] Invert Binary Tree
*
* https://leetcode.com/problems/invert-binary-tree/description/
*
* algorithms
* Easy (78.10%)
* Likes: 14546
* Dislikes: 241
* Total Accepted: 2.6M
* Total Submissions: 3.2M
* Testcase Example: '[4,2,7,1,3,6,9]'
*
* Given the root of a binary tree, invert the tree, and return its root.
*
*
* Example 1:
*
*
* Input: root = [4,2,7,1,3,6,9]
* Output: [4,7,2,9,6,3,1]
*
*
* Example 2:
*
*
* Input: root = [2,1,3]
* Output: [2,3,1]
*
*
* Example 3:
*
*
* Input: root = []
* Output: []
*
*
*
* Constraints:
*
*
* The number of nodes in the tree is in the range [0, 100].
* -100 <= Node.val <= 100
*
*
*/

// @lc code=start
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* invertTree(TreeNode* root)
{
if (!root) return NULL;

swap(root->left, root->right);

invertTree(root->left);
invertTree(root->right);
return root;
}
};
// @lc code=end
  • T: O(N)O(N)

  • S: O(H)O(H)

  • Iteration

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* invertTree(TreeNode* root)
{
if (!root) return NULL;
queue<TreeNode*> q;
q.push(root);
while (!q.empty())
{
TreeNode* node = q.front(); q.pop();

swap(node->left, node->right);

if(node->left) q.push(node->left);

if(node->right) q.push(node->right);
}
return root;
}
};
  • T: O(N)O(N)
  • S: O(N)O(N)