Iterative sol solution. 3 ms as per leetcode.


  • 0
    B

    public boolean isSymmetric(TreeNode root) {
    if(root == null)
    return true;
    if(root.left ==null && root.right == null)
    return true;

        if(root.left == null ^ root.right == null)
        return false;
        
        Stack<TreeNode> stack = new Stack<TreeNode>();
        stack.push(root.right);
        stack.push(root.left);
        while(!stack.isEmpty()){
            if(stack.size() % 2> 0)
            return false;
            
            TreeNode lnode = stack.pop();
            TreeNode rnode = stack.pop();
            
            if(lnode.val != rnode.val)
            return false;
            
            if(rnode.right !=null)
            stack.push(rnode.right);
            if(lnode.left !=null)
            stack.push(lnode.left);
            
            if(stack.size() % 2> 0)
            return false;
            if(lnode.right !=null)
            stack.push(lnode.right);
            if(rnode.left !=null)
            stack.push(rnode.left);
        }
        
        return true;
        
    }

Log in to reply
 

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