问题描述:翻转一棵二叉树
样例:
1 1
/ \ / \
2 3 => 3 2
/ \
4 4
实现代码:
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: a TreeNode, the root of the binary tree
* @return: nothing
*/
void invertBinaryTree(TreeNode *root) {
// write your code here
TreeNode *temp;
if(root==NULL)
return;
else
{
temp=root->right;
root->right=root->left;
root->left=temp;
invertBinaryTree(root->left);
invertBinaryTree(root->right);
}
//swap(root->left,root->right);
//invertBinaryTree(root->left);
//invertBinaryTree(root->right); 大神给讲的swap()函数
}
};
做题感想:此题要注意定义的temp变量是局部变量。做完后看别的同学做的更简单,是什么swap()函数,好吧以前没好好学,不知道是啥。