题目描述
操作给定的二叉树,将其变换为源二叉树的镜像。
输入描述:
二叉树的镜像定义:源二叉树
8
/ \
6 10
/ \ / \
5 7 9 11
镜像二叉树
8
/ \
10 6
/ \ / \
11 9 7 5
/**
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){
//创建临时结点,交换左右结点
TreeNode tempNode=null;
tempNode=root.left;
root.left=root.right;
root.right=tempNode;
Mirror(root.left);
Mirror(root.right);
}
}
}
本文介绍了一种通过递归实现的二叉树镜像变换算法。该算法将一棵二叉树转换为其镜像,即左右子树互换位置。通过对二叉树节点进行递归处理,可以高效地完成变换过程。
2138

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



