判断二叉树是否为对称的二叉树
问题描述:判断二叉树是否为对称的二叉树,如果一棵二叉树和其镜像二叉树一样,那么它就是对称的
首先考察基本功,二叉树镜像、前序遍历等,我们可以写一个镜像二叉树的函数,然后判断两棵二叉树是否一样,如果一样则说明正确,二叉树镜像的函数在上一篇写过了,这里不赘述了,这里采用一种特殊的遍历方法的方法。
本方法思想:定义一个前序遍历和对称的前序遍历方法,如果遍历结果一样则对称(要考虑到空指针。。),不考虑空指针会出错,比如一个树是7.left=7;另一个是7.right=7,无论怎么遍历结果都一样,如果考虑空指针则可以正确判断
持续更新...
代码附下
Java实现:
package 判断二叉树是否对称;
/**
* 如果一个二叉树和它的镜像一样,就是对称二叉树
* @author user
*思路1:将二叉树镜像
*思路2:定义一个前序遍历和对称的前序遍历方法
*如果遍历结果一样则对称(要考虑到空指针。。)
*不考虑空指针会出错,比如一个树是7.left=7;另一个是7.right=7
*无论怎么遍历结果都一样
*/
二叉树的数据结构:
public class BinaryTree {
int val;
BinaryTree left = null;
BinaryTree right = null;
public BinaryTree(int val) {
this.val = val;
}
}
public class Test {
public static boolean isSymmetrical(BinaryTree root1, BinaryTree root2) {
if (root1 == null && root2 == null) {
return true;
}
if (root1 == null || root2 == null) {
return false;
}
if (root1.val != root2.val) {
return false;
}
//判断A的左边和B的右边是否相等,判断A的右边和B的左边是否相等,都相等就满足
return isSymmetrical(root1.left, root2.right) && isSymmetrical(root1.right, root2.left);
}
public static void main(String[] args) {
BinaryTree rootA = new BinaryTree(8);
rootA.left = new BinaryTree(9);
rootA.right = new BinaryTree(9);
// rootA.left.left=new BinaryTree(9);
// rootA.left.right=new BinaryTree(2);
// rootA.left.right.left=new BinaryTree(4);
// rootA.left.right.right=new BinaryTree(7);
System.out.println(isSymmetrical(rootA, rootA));//测试
}
}
持续更新...欢迎赞赏!
主页:https://blog.youkuaiyun.com/ustcer_93lk/article/details/80374008
如果有问题,欢迎大家留言,有更好的方法也期待大家告知。