My solution using post-order traversal and recursion (3ms)


  • 0
    L
    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;
            ArrayList<Integer> leftList = new ArrayList();
            ArrayList<Integer> rightList = new ArrayList();
            leftTraverse (leftList, root.left);
            rightTraverse (rightList, root.right);
            
            if (leftList.size() != rightList.size()) return false;
            for(int i = 0; i<leftList.size(); i++) {
                if (leftList.get(i) != rightList.get(i)) return false;
            }
            return true;
    }
        
    public void leftTraverse (ArrayList<Integer> list, TreeNode node) {
            // left postorder traversal
            if (node == null) {
                list.add(null);
                return;
                
            }
            leftTraverse(list, node.left);
            leftTraverse(list, node.right);
            list.add(node.val);
    }
        
    public void rightTraverse (ArrayList<Integer> list, TreeNode node) {
            // right postorder traversal
            if (node == null) {
                list.add(null);
                return;
                
            }
            rightTraverse(list, node.right);
            rightTraverse(list, node.left);
            list.add(node.val);
    }
    

Log in to reply
 

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