Iterative java solution


  • 0
    J
    /**
     * 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;
            }
            List<TreeNode> currNodeList =new ArrayList<TreeNode>();
            currNodeList.add(root);
            while(currNodeList.size()!=0){
                List<TreeNode> nextNodeList =new ArrayList<TreeNode>();
                for (int i=0; i<currNodeList.size(); i++){
                    TreeNode leftNode = currNodeList.get(i);
                    TreeNode rightNode = currNodeList.get(currNodeList.size()-1-i);
                    if (leftNode.left==null^rightNode.right==null){
                        return false;
                    }
                    if (leftNode.val!=rightNode.val){
                        return false;
                    }
                    if (leftNode.left!=null){
                        nextNodeList.add(leftNode.left);
                    }
                    if (leftNode.right!=null){
                        nextNodeList.add(leftNode.right);
                    }
                }
                currNodeList = nextNodeList;
            }
            return true;
        }
    }

Log in to reply
 

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