Java Solution both recursive and iterative!!!!


  • 0
    A
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public boolean isSymmetric(TreeNode root) {
            if (root == null){
                return true;
            }
            return isSymmetricIter (root.left,root.right);
        }
        
        public boolean isSymmetric (TreeNode left,TreeNode right){
            if (left == null && right == null){
                return true;
            }
            else if (left == null || right == null){
                return false;
            }
            else if (left.val == right.val){
                return isSymmetric (left.left,right.right) && isSymmetric (left.right, right.left);
            }
            else {
                return false;
            }
        }
        
        public boolean isSymmetricIter (TreeNode left, TreeNode right){
            Stack<TreeNode> s1 = new Stack<TreeNode>();
            Stack<TreeNode> s2 = new Stack<TreeNode>();
            
            TreeNode p = left;
            TreeNode q = right;
            
            while ((!s1.isEmpty() || p != null) && (!s2.isEmpty() || q != null)){
                if (p != null && q != null){
                    s1.push (p);
                    p = p.left;
                    s2.push (q);
                    q = q.right;
                }
                else if (p != null || q != null){
                    return false;
                }
                else {
                    TreeNode pTemp = s1.pop ();
                    TreeNode qTemp = s2.pop ();
                    if (pTemp.val == qTemp.val){
                        p = pTemp.right;
                        q = qTemp.left;
                    }
                    else {
                        return false;
                    }
                }
            }
            if ((p == null && q == null) && (s1.isEmpty() && s2.isEmpty())){
                return true;
            }
            return false;
        }
    }

Log in to reply
 

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