分享一种非递归算法,主要思路是:设置两个链表,分别代表左子树右子树。左子树每次都从左往右添加节点,右子树每次都从右往左添加节点。

import java.util.LinkedList;

public class Solution {
   boolean isSymmetrical(TreeNode pRoot)
    {
        if (pRoot == null)
            return true;
        LinkedList<TreeNode> leftList = new LinkedList<>();
        LinkedList<TreeNode> rightList = new LinkedList<>();
        leftList.add(pRoot.left);
        rightList.add(pRoot.right);
        while (!leftList.isEmpty() && !rightList.isEmpty()) {
            TreeNode leftNode = leftList.poll();
            TreeNode rightNode = rightList.poll();
            if (leftNode == null && rightNode == null)
                continue;
            if (leftNode == null || rightNode == null)
                return false;
            if (leftNode.val != rightNode.val)
                return false;
            // 左子树从左往右添加节点
            leftList.add(leftNode.left);
            leftList.add(leftNode.right);
            // 右子树从右往左添加节点
            rightList.add(rightNode.right);
            rightList.add(rightNode.left);
        }
        return leftList.isEmpty() && rightList.isEmpty();
    }
}