一、问题描述
翻转一棵二叉树
样例
1 1
/ \ / \
2 3 => 3 2
/ \
4 4
运用递归算法,前序遍历此二叉树的左右子树,然后运用swap函数交换左右子树即可。
三、我的代码
class Solution {
public:
/**
* @param root: a TreeNode, the root of the binary tree
* @return: nothing
*/
void invertBinaryTree(TreeNode *root) {
if(root==NULL) return;
swap(root->left,root->right);
invertBinaryTree(root->left);
invertBinaryTree(root->right);
}
};
四、我的感想
做这道题首先想到交换运用的swap函数,然后问题就简单化了,以前的知识到现在依然很有用,想到有必要去翻翻以前的课本了。