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
思路:设两个游标p,q同时递归,递归的方向相反。即当p往左走时,q往右走。p往右走时,q往左走。
如果这棵树是镜像的,那么最后 p 和 q一定是同时到达null位置,并且在这个过程中,p,q节点的
值是相同的。
/** * 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 judge(root.left,root.right); } private boolean judge(TreeNode p,TreeNode q){ if (p==null&&q==null) //同时到达null位置,说明树是镜像的 return true; if (p==null&&q!=null) return false; if (p!=null&&q==null) return false; if (p.val!=q.val) return false; return judge(p.left,q.right)&&judge(p.right,q.left); } }