Invert Binary Tree Solutions in C++
Number 226
Difficulty Easy
Acceptance 65.1%
Link LeetCode
Solutions
C++ solution by haoel/leetcode
// Source : https://leetcode.com/problems/invert-binary-tree/// Author : Hao Chen// Date : 2015-06-12/*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode(int x) : val(x), left(NULL), right(NULL) {}* };*/class Solution {public:TreeNode* invertTree_recursive(TreeNode* root) {if (root==NULL) return root;TreeNode* node = invertTree_recursive(root->left);root->left = invertTree_recursive(root->right);root->right = node;return root;}TreeNode* invertTree_non_recursive(TreeNode* root) {if (root==NULL) return root;vector<TreeNode*> stack;stack.push_back(root);while (!stack.empty()) {TreeNode* node = stack.back();stack.pop_back();swap(node->left, node->right);if (node->left) stack.push_back(node->left);if (node->right) stack.push_back(node->right);}return root;}TreeNode* invertTree(TreeNode* root) {if (rand()%2){return invertTree_non_recursive(root);}return invertTree_recursive(root);}};
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/invert-binary-tree/description//// Author : liuyubobobo/// Time : 2017-11-17#include <iostream>using namespace std;/// Definition for a binary tree node.struct TreeNode {int val;TreeNode *left;TreeNode *right;TreeNode(int x) : val(x), left(NULL), right(NULL) {}};/// Recursive/// Time Complexity: O(n), where n is the node's number of the tree/// Space Complexity: O(h), where h is the height of the treeclass Solution {public:TreeNode* invertTree(TreeNode* root) {if(root == NULL)return NULL;invertTree(root->left);invertTree(root->right);swap(root->left, root->right);return root;}};int main() {return 0;}
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/invert-binary-tree/description//// Author : liuyubobobo/// Time : 2017-11-17#include <iostream>#include <queue>using namespace std;/// Definition for a binary tree node.struct TreeNode {int val;TreeNode *left;TreeNode *right;TreeNode(int x) : val(x), left(NULL), right(NULL) {}};/// Non-Recursive/// Time Complexity: O(n), where n is the node's number of the tree/// Space Complexity: O(n)class Solution {public:TreeNode* invertTree(TreeNode* root) {if(root == NULL)return NULL;queue<TreeNode*> q;q.push(root);while(!q.empty()){TreeNode* curNode = q.front();q.pop();swap(curNode->left, curNode->right);if(curNode->left)q.push(curNode->left);if(curNode->right)q.push(curNode->right);}return root;}};int main() {return 0;}