Java simple solution, compare in-order and reversed in-order traversal.

  • 2

    Use two pointers (p, q), traverse the tree simultaneously, p goes in-order while q goes reversed in-order, compare along the way. It can be done with pre-order and reversed pre-order or post-order and reversed post-order as well.

    public boolean isSymmetric(TreeNode root) {
        return traverse(root, root);
    private boolean traverse(TreeNode p, TreeNode q) {
    	if (p == null && q == null) return true;
    	if (p == null || q == null) return false;
    	if (!traverse(p.left, q.right)) 
    		return false;
    	if (p.val != q.val) return false;
    	return traverse(p.right, q.left);

Log in to reply

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