1、问题描述
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3]
is symmetric:
1 / 2 2 / / 3 4 4 3
But the following [1,2,2,null,3,null,3]
is not:
1 / 2 2 3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
2、边界条件:root==null
3、思路:1)递归,对称结构是镜像;左手和右手的关系。所以应该左子树和右子树比较,右子树和左子树比较是否相同same。但是首先,从root开始分为左右子树。
base case:左右都为空--true,左右有一个为空--false
2)迭代:一层一层的比较,可以利用队列,前后取值比较是否相同。
4、代码实现
1)递归
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public boolean isSymmetric(TreeNode root) { if (root == null) { return true; } return isSameTree(root.left, root.right); } public boolean isSameTree(TreeNode p, TreeNode q) { if (p == null && q == null) { return true; } if (p == null || q == null) { return false; } return p.val == q.val && isSameTree(p.left, q.right) && isSameTree(p.right, q.left); } }
2)迭代
5、api