题目描述
Invert a binary tree.
Example:
Input:
4
/
2 7
/ \ /
1 3 6 9
Output:
4
/
7 2
/ \ /
9 6 3 1
代码
递归
#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 tree
class 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;
}
思路二
#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;
}