递归一直不熟,没想出来,写的算法跑不通
看了下别人的算法
C++,我的,仔细看了下,和答案思路一样,可能是交换左右节点的代码有问题
/**
* 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==NULL)
return root;
else
{
invertTree(root->left);
invertTree(root->right);
TreeNode *tmp;
tmp->val=root->left->val;
root->left->val=root->right->val;
root->right->val=tmp->val;
}
return root;
}
};
C++,答案,递归
/**
* 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) {
invertTree(root->left);
invertTree(root->right);
std::swap(root->left, root->right);
}
return root;
}
};
C++,看了答案之后修改了代码,原来是交换节点只交换了数值,没有彻底交换
/**
* 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)
{
invertTree(root->left);
invertTree(root->right);
TreeNode *tmp;
tmp=root->left;
root->left=root->right;
root->right=tmp;
}
return root;
}
};
Java,看了答案后修改
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode invertTree(TreeNode root) {
if(root==null)
return root;
else
{
invertTree(root.left);
invertTree(root.right);
TreeNode tmp=root.left;
root.left=root.right;
root.right=tmp;
}
return root;
}
}
Javascript,看了答案后修改
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {TreeNode}
*/
var invertTree = function(root) {
if(root===null)
return root;
else
{
invertTree(root.left);
invertTree(root.right);
var tmp=root.left;
root.left=root.right;
root.right=tmp;
}
return root;
};
C++,非递归,栈
/**
* 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) {
std::stack<TreeNode*> stk;
stk.push(root);
while (!stk.empty()) {
TreeNode* p = stk.top();
stk.pop();
if (p) {
stk.push(p->left);
stk.push(p->right);
std::swap(p->left, p->right);
}
}
return root;
}
};