Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【leetcode】Q101对称二叉树 #4

Open
0xbitboy opened this issue Jan 30, 2019 · 1 comment
Open

【leetcode】Q101对称二叉树 #4

0xbitboy opened this issue Jan 30, 2019 · 1 comment

Comments

@0xbitboy
Copy link
Owner

0xbitboy commented Jan 30, 2019

leetcode:Q101
给定一个二叉树,检查它是否是镜像对称的。

例如,二叉树 [1,2,2,3,4,4,3] 是对称的。

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

但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:

    1
   / \
  2   2
   \   \
   3    3
@0xbitboy
Copy link
Owner Author

递归的解法:
2个树是否镜像对称看需要满足以下2点:

  1. 当前节点相等
  2. 左节点等于另一树的右节点,右节点等于另一个树的左节点
  3. 递归执行1和2.

class Solution {
	public boolean isSymmetric(TreeNode root) {
		if(root == null ){
			return true;
		}
		return  isSymmetric(root.left,root.right);
	}

	/**
	 * 对于2个数是否是对称的,只要满足根-> 左 -> 右 与 另一个树的 根-> 右 -> 左 的值一样即可。
	 * 也就是每个节点比较当前节点是否相同,再分2路分表比较4个子节点是否对称。
	 * @param left
	 * @param right
	 * @return
	 */

	private boolean isSymmetric(TreeNode left ,TreeNode right){
		if(left == null && right == null){
			return true;
		}
		if (left == null || right ==null){
			return false;
		}
		return left.val == right.val &&  isSymmetric(left.right,right.left) && isSymmetric(left.left,right.right);
	}
}

0xbitboy added a commit that referenced this issue Jan 30, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant