题目
思路
递归实现:
①终止条件:递归到空节点直接返回。
②转换为子问题:翻转二叉树等于翻转左子树和右子树,并且将左子树根的值和右子树根的值交换。
代码
typedef struct TreeNode BTNode;
void Swap(BTNode** left, BTNode** right)
{
BTNode* tmp = *left;
*left = *right;
*right = tmp;
}
void _invertTree(BTNode* root)
{
if (root == NULL)
return;
_invertTree(root->left);//翻转左子树
_invertTree(root->right);//翻转右子树
Swap(&root->left, &root->right);//交换左右子树的值
}
struct TreeNode* invertTree(struct TreeNode* root){
_invertTree(root);
return root;
}