一、题目内容

image.png

二、题解

解法1:

思路

递归

代码

  1. public class Solution {
  2. public boolean isSymmetric (TreeNode root) {
  3. // write code here
  4. return check(root,root);
  5. }
  6. public boolean check(TreeNode n1,TreeNode n2){
  7. if(n1 == null && n2 == null){
  8. return true;
  9. }
  10. if(n1==null||n2==null){
  11. return false;
  12. }
  13. return n1.val == n2.val && check(n1.left,n2.right) && check(n1.right,n2.left);
  14. }
  15. }

解法2:

思路

迭代

代码

迭代法

  1. public class Solution {
  2. public boolean isSymmetric (TreeNode root) {
  3. // write code here
  4. return check(root,root);
  5. }
  6. public boolean check(TreeNode n1,TreeNode n2){
  7. Stack<TreeNode> stack = new Stack<TreeNode>();
  8. stack.push(n1);
  9. stack.push(n2);
  10. while(!stack.isEmpty()){
  11. n1 = stack.pop();
  12. n2 = stack.pop();
  13. if (n1 == null && n2 == null) {
  14. continue;
  15. }
  16. if ((n1 == null || n2 == null) || n1.val != n2.val) {
  17. return false;
  18. }
  19. stack.push(n1.left);
  20. stack.push(n2.right);
  21. stack.push(n1.right);
  22. stack.push(n2.left);
  23. }
  24. return true;
  25. }
  26. }