《剑指offer》练习-面试题28-对称的二叉树

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

package offer;

public class Solution28 {
	boolean isSymmetrical(TreeNode pRoot) {
		if (pRoot == null)
			return true;

		return f(pRoot.left, pRoot.right);
	}

	boolean f(TreeNode root1, TreeNode root2) {
		// 考虑到空指针
		if (root1 == null && root2 == null)
			return true;

		// 两边都不为空指针
		// 内容要相等,且root1.left==root2.right和root1.right==root.left。如此往复。
		if (root1 != null && root2 != null)
			return root1.val == root2.val && f(root1.left, root2.right) && f(root1.right, root2.left);

		return false;
	}

}

猜你喜欢

转载自blog.csdn.net/sinat_34548226/article/details/81228622