My stack dsf solution


  • 0
    C
    public class Solution {
    public boolean isSymmetric(TreeNode root) {
        if(root == null || ((root.left == null) && (root.right == null)))
            return true;
        
        Stack <TreeNode> s1 = new Stack <TreeNode>();
        Stack <TreeNode> s2 = new Stack <TreeNode>();
        
        if(root.left == null || root.right == null)
            return false;
        
        s1.add(root.left); 
        s2.add(root.right);
        
        while(s1.isEmpty() == false && s2.isEmpty() == false)
        {
         
         TreeNode t1 = s1.pop();
         TreeNode t2 = s2.pop();
         if(t1.val != t2.val)
            return false;
         if(t1.left != null && t2.right != null)
         {
            s1.add(t1.left);
            s2.add(t2.right);
         }
         if(t1.right != null && t2.left != null)
         {
            s1.add(t1.right);
            s2.add(t2.left);
         }
         if((t1.left == null && t2.right != null) || (t1.left != null && t2.right == null) || (t1.right != null && t2.left == null) || (t1.right == null && t2.left != null))
            return false;
        }
        return true;
    }
    

    }


Log in to reply
 

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