[LeetCode]Symmetric Tree

题目描述

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree is symmetric:

    1
   / \
  2   2
 / \ / \
3  4 4  3

But the following is not:

    1
   / \
  2   2
   \   \
   3    3
判断一个二叉树是否是镜面对称。

解题思路

递归,保存左右两个节点,然后判断leftNode.left和rightNode.right,以及leftNode.right和rightNode.left。如此不断递归


误区:
不要看到题目就想到按层遍历,然后看每层的节点是否对称,这样思路不够简洁。


代码


       /**
	 * 判断一个二叉树是否是镜面对称
	 * @param root
	 * @return
	 */
	public static boolean isSymmetric(TreeNode root) {
		if (root == null)
			return true;
		return check(root.left, root.right);
	}

	/**
	 * 递归判断一个二叉树是否是镜面对称
	 * @param left
	 * @param right
	 * @return
	 */
	public static boolean check(TreeNode left, TreeNode right) {
		if (left == null && right == null) {
			return true;
		}

		if (left == null || right == null) {
			return false;
		}

		return left.val == right.val && check(left.left, right.right)
				&& check(left.right, right.left);
	}



你可能感兴趣的:([LeetCode]Symmetric Tree)