题目描述
操作给定的二叉树,将其变换为源二叉树的镜像。
二叉树的镜像定义:源二叉树
8
/ \
6 10
/ \ / \
5 7 9 11
镜像二叉树
8
/ \
10 6
/ \ / \
11 9 7 5
解题思路
交换当前结点的左右结点后,整个左右子树也是交换了的,见下图:
代码
// 递归
public void Mirror(TreeNode root) {
if (root == null) return;
if (root.left == null && root.right == null) return;
// 交换当前结点的左右子树
TreeNode tempNode = root.left;
root.left = root.right;
root.right = tempNode;
if (root.left != null) {
Mirror(root.left);
}
if (root.right != null) {
Mirror(root.right);
}
}
// 非递归
public void Mirror(TreeNode root) {
if (root == null) return;
if (root.left == null && root.right == null) return;
Stack<TreeNode> stack = new Stack<>();
// 先将根结点压人栈中
stack.push(root);
while(!stack.isEmpty()) {
// 取出栈顶元素,即当前的根结点
TreeNode node = stack.pop();
// 交换左右子树
if (node.left != null || node.right != null) {
TreeNode tempNode = node.left;
node.left = node.right;
node.right = tempNode;
}
// 若当前结点有左结点,压人栈中
if (node.left != null) {
stack.push(node.left);
}
// 若当前结点有右结点,压人栈中
if (node.right != null) {
stack.push(node.right);
}
}
}
文章汇总见这里 >>剑指Offer汇总<<
更多精彩文章见这里 >>我的学习小站<< & 更多好玩见这里 >>技术杂谈<<