题目:
Invert a binary tree.
4
/ \
2 7
/ \ / \
1 3 6 9
to
4
/ \
7 2
/ \ / \
9 6 3 1
代码:
自己的(递归实现):
/**
* 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(TreeNode* root) {
TreeNode* tem;
if (!root)
return 0;
tem = root->left;
root->left = root->right;
root->right = tem;
if(root->left)
invertTree(root->left);
if(root->right)
invertTree(root->right);
return root;
}
};
别人的:
/**
* 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(TreeNode* root) {
if (root){
swap(root->left, root->right);
invertTree(root->left);
invertTree(root->right);
}
return root;
}
};
自己的(使用队列,非递归实现):
/**
* 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(TreeNode* root) {
queue<TreeNode*> queue;
if(!root)
return 0;
queue.push(root);
TreeNode *curNode;
while(!queue.empty()){
curNode = queue.front();
queue.pop();
swap(curNode->left, curNode->right);
if(curNode->left)
queue.push(curNode->left);
if(curNode->right)
queue.push(curNode->right);
}
return root;
}
};
非递归和递归的在LeetCode上运行效率差不多。。。