第十七题:二叉树的镜像
题目描述
操作给定的二叉树,将其变换为源二叉树的镜像。
输入描述:
二叉树的镜像定义:
源二叉树
8
/ \
6 10
/ \ / \
5 7 9 11
镜像二叉树
8
/ \
10 6
/ \ / \
11 9 7 5
解析:
此题直观的解法是使用递归的方式,将根节点的每个左右子节点进行swap。下图中介绍了使用栈空间的解法
注意:
①代码的鲁棒性(极限条件的考虑,空树条件)
②每次弹出栈顶元素,并且判断该元素的左右孩子结点,做swap操作
③结束条件为栈空间为空
具体实现如下图所示:
具体实现代码如下:
//非递归写法
public class Solution {
public void Mirror(TreeNode root) {
//代码的鲁棒性
if(root == null){
return;
}
//使用额外空间栈
Stack<TreeNode> stack = new Stack<TreeNode>();
//压入根节点
stack.push(root);
while(!stack.isEmpty()){
//弹出栈顶元素
TreeNode node = stack.pop();
//交换左右孩子结点
if(node.left != null||node.right != null){
TreeNode temp = node.left;
node.left = node.right;
node.right = temp;
}
//压入根结点的左右孩子结点
if(node.left!=null){
stack.push(node.left);
}
if(node.right!=null){
stack.push(node.right);
}
}
}
}
//递归写法
public void Mirror(TreeNode root){
//代码的鲁棒性
if (root == null){
return;
}
//case
if (root.left == null && root.right == null){
return;
}
//交换结点
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
//左右结点继续进行交换
if (root.left != null){
Mirror(root.left);
}
if (root.right != null){
Mirror(root.right);
}
}
/**
* 功能描述: <br>
*〈TreeNode节点类〉
* @since: 1.0.0
* @Author: 一个鲁肃
*/
class TreeNode {
public int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}