题目描述
操作给定的二叉树,将其变换为源二叉树的镜像。
输入描述:
二叉树的镜像定义:源二叉树
8
/ \
6 10
/ \ / \
5 7 9 11
镜像二叉树
8
/ \
10 6
/ \ / \
11 9 7 5
解题思路
遇到树的问题还是选择用递归方式来解决,首先观察题目,镜像二叉树就是将每个节点的左右子树交换位置即可,那么用递归就是最佳的方法,用中间值保存当前左右子树的值,再将二者交换位置后连接到当前节点上。具体代码如下:
public class Solution {
public void Mirror(TreeNode root) {
if(root == null){
return ;
}
root = convert(root);
}
public TreeNode convert(TreeNode root){
if(root == null){
return null;
}
TreeNode newleft = convert(root.right);
TreeNode newright = convert(root.left);
root.left = newleft;
root.right = newright;
return root;
}
}
总结
用灵活运用递归解决树的问题。
转载:https://blog.csdn.net/qq_34791579/article/details/102017674
查看评论