操作给定的二叉树,将其变换为源二叉树的镜像。
数据范围:二叉树的节点数 0 \le n \le 10000≤n≤1000 , 二叉树每个节点的值 0\le val \le 10000≤val≤1000
要求: 空间复杂度 O(n)O(n) 。本题也有原地操作,即空间复杂度 O(1)O(1) 的解法,时间复杂度 O(n)O(n)
void pre_order(struct TreeNode* pRoot, struct TreeNode* temp){
if(pRoot == NULL){
return;
}
temp = pRoot->left;
pRoot->left = pRoot->right;
pRoot->right = temp;
pre_order(pRoot->left, temp);
pre_order(pRoot->right, temp);
}
struct TreeNode* Mirror(struct TreeNode* pRoot ) {
struct TreeNode *temp = NULL;
pre_order(pRoot, temp);
return pRoot;
}
所有节点的左右子节点互换,用前序遍历,依次互换即可