using System ;
using System. Collections. Generic ;
namespace 剑指_Offer_27. _二叉树的镜像
{
class Program
{
public class TreeNode
{
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode ( int x) { val = x; }
}
public static TreeNode MirrorTree ( TreeNode root)
{
if ( root == null ) return null ;
if ( root. left == null && root. right == null ) return root;
TreeNode temp = root. left;
root. left = root. right;
root. right = temp;
MirrorTree ( root. left) ;
MirrorTree ( root. right) ;
return root;
}
static TreeNode creat ( )
{
TreeNode p;
int num = Console. Read ( ) ;
if ( num == '#' ) p = null ;
else
{
p = new TreeNode ( num - 48 ) ;
p. left = creat ( ) ;
p. right = creat ( ) ;
}
return p;
}
static void debug ( TreeNode A)
{
if ( A == null ) return ;
Console. Write ( A. val) ;
debug ( A. left) ;
debug ( A. right) ;
}
static void Main ( string [ ] args)
{
TreeNode A = creat ( ) ;
A= MirrorTree ( A) ;
debug ( A) ;
}
}
}
要点说明
对象的引用传递:当函数中对引用指向发生改变后,源引用的对象不会随之变化,因为引用发生了改变 out参数:可以使用out,在函数最后会将值赋值给之前的引用对象,这样可以保证引用的一致性 MirrorTree函数第一句代码不可省略 当省略第一句时,root==null是,对root.left的引用是错误的。