算法题(三十六):对称的二叉树

版权声明:转载请注明来处 https://blog.csdn.net/qq_24034545/article/details/84344608

题目描述

请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。

分析

从上而下递归扫描,只要发现左右结点不相同的返回false。

代码

public class Symmetry {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		TreeNode root = new TreeNode(1);
		root.left = new TreeNode(1);
		root.right = new TreeNode(1);
		root.left.left= new TreeNode(3);
		root.left.right = new TreeNode(3);
		root.right.left = new TreeNode(3);
		root.right.right = new TreeNode(3);
		System.out.println(symmetry(root));
	}
	
	public static boolean symmetry(TreeNode root){
		if(root == null){
			return true;
		}
		return comRoot(root.left, root.right);
		
	}
    private static boolean comRoot(TreeNode left, TreeNode right) {
        // TODO Auto-generated method stub
        if(left == null) return right==null;
        if(right == null) return false;
        if(left.value != right.value) return false;
        return comRoot(left.right, right.left) && comRoot(left.left, right.right);
    }

}

猜你喜欢

转载自blog.csdn.net/qq_24034545/article/details/84344608