Why don't you use two stack which much easier to understand!


  • 2
    G
     public class Solution{
     public boolean isSymmetric(TreeNode root){
         Stack<TreeNode> s1 = new Stack<TreeNode>();
         Stack<TreeNode> s2 = new Stack<TreeNode>();
         if(root == null)   return true;
         s1.push(root); s2.push(root);
         while(!s1.isEmpty() && !s2.isEmpty()){
             TreeNode n1 = s1.pop();
             TreeNode n2 = s2.pop();
             if(n1.val != n2.val)   return false;
             if(n1.left != null && n2.right != null){
                 s1.push(n1.left);
                 s2.push(n2.right);
             }
             if(n1.right != null && n2.left != null){
                 s1.push(n1.right);
                 s2.push(n2.left);
             }else if((n1.left == null && n2.right == null) || (n1.right == null && n2.left ==null))
                continue;
              else return false;
         }
         return true;
     }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.