第一个
操作给定的二叉树,将其变换为源二叉树的镜像。
思路非常简单,排除两种特殊情况,然后创建一个临时变量进行交换.
具体看代码,不进行赘述
public TreeNode Mirror (TreeNode pRoot) {
// write code here
if(pRoot==null)return null;//树为空
if(pRoot.left==null&&pRoot.right==null)return pRoot;//只有根节点
TreeNode cur;//定义的临时变量
//交换
cur=pRoot.left;
pRoot.left=pRoot.right;
pRoot.right=cur;
//递归
Mirror(pRoot.left);
Mirror(pRoot.right);
return pRoot;
}
第二个
给定一个二叉树,检查它是否是镜像对称的。
思路很简单,排除三种特殊情况,进行递归遍历
class Solution {
public boolean SameTree(TreeNode leftTree,TreeNode rightTree){
//左树或右树为空的情况
if(leftTree!=null&&rightTree==null||leftTree==null&&rightTree!=null){
return false;
}
//左右树都为空
if(leftTree==null&&rightTree==null){
return true;
}
//节点值不相同
if(leftTree.val!=rightTree.val){
return false;
}
//递归遍历
return SameTree(leftTree.left,rightTree.right)&&SameTree(leftTree.right,rightTree.left);
}
public boolean isSymmetric(TreeNode root) {
//判空
if(root==null){
return false;
}
//传进去两个参数
return SameTree(root.left,root.right);
}
}