1.问题描述
翻转一棵二叉树
样例
1 1
/ \ / \
2 3 => 3 2
/ \
4 4
2.解题思路
翻转就是把右节点赋给左节点,把左节点赋给右节点,然后递归所有节点,进行翻转操作。
3.代码实现
/**
* 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->left;
root->left=root->right;
root->right=temp;
invertBinaryTree(root->left);
invertBinaryTree(root->right);
}
}
};
4.感想
注意判空后,先赋值,后遍历。