《剑指offer》 二叉树的镜像

时间:2023-03-09 00:12:52
《剑指offer》 二叉树的镜像

本题来自《剑指offer》二叉树的镜像

题目:

  操作给定的二叉树,将其变换为源二叉树的镜像。
 二叉树的镜像定义:源二叉树
8
/ \
6 10
/ \ / \
5 7 9 11
镜像二叉树
8
/ \
10 6
/ \ / \
11 9 7 5

思路:

   关于树,如果思路不够明确,可以画出图标辅助理解题目。

  画出几步就会得出通用的思路,镜像发现如果通过交换左右子节点,左子树又是树,右子树又是树。可以采用递归的思路。

  递归需要找到结束条件,如果根节点是是空或者当为子节点时候便结束本次递归。

C++ Code:

/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
void Mirror(TreeNode *pRoot) {
if (!pRoot){ //根节点如果为空,返回
return ;
}
if (!pRoot->left && !pRoot->right){ //如果为子节点,返回
return ;
}
TreeNode* temp; //交换左右子节点
temp = pRoot->left;
pRoot->left = pRoot->right;
pRoot->right = temp;
if (pRoot->left){ //如果左节点不空,则调用左子树
Mirror(pRoot->left);
}
if (pRoot->right){ //如果右子树不空,则调用右子树
Mirror(pRoot->right);
}
}
};

Python Code:

# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回镜像树的根节点
def Mirror(self, root):
# write code here
if not root: #边界条件,空节点直接返回
return None
if not root.left and not root.right: #若为子节点,返回空
return None
root.left,root.right = root.right,root.left #将左右子节点交换
if root.left:
self.Mirror(root.left) #递归调用左子树
if root.right:
self.Mirror(root.right) #递归调用右子树
return root #返回根节点

总结:

  三思后行。

  写代码之前将思路理顺,首先大的方向要正确的基础上,在确定小的细节。比如边界条件,要有防御性的代码考虑。