题目描述
操作给定的二叉树,将其变换为源二叉树的镜像。

解题思路
递归:找到每一个节点(非叶子节点)调换其左、右孩子。
代码实现
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public void Mirror(TreeNode root) {
if(root == null) return;
if(root.left == null && root.right == null) return;
if(root != null){
TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp;
if(root.left != null){
Mirror(root.left);
}
if(root.right != null){
Mirror(root.right);
}
}
}
}
本文介绍了一种通过递归方式将二叉树转换为其镜像的方法。核心思想在于交换每个非叶子节点的左右子节点,然后分别对新的左右子树进行相同的操作,直至遍历完整棵树。
6万+

被折叠的 条评论
为什么被折叠?



