一.题目描述
翻转一棵二叉树
样例
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
if(root==NULL) return;
TreeNode *f=new TreeNode;
f=root->left;
root->left=root->right;
root->right=f;
invertBinaryTree(root->right);
invertBinaryTree(root->left);
}
};
四.感悟
在将根节点的左右子树翻转的时候要注意申请一个新的节点用来保存左子树.