Is there any error in it,please tell me

  • 0
    public boolean isSymmetric(TreeNode root) {
        if(root == null) return true;
        TreeNode tmp = reverse(root);
        if(tmp == root){
            return true;
        return false;
    private TreeNode reverse(TreeNode root){
        if(root == null) return root;
        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;
        return root;

  • 2

    You code seems reverse any nodes in the tree, when it is a leaf node the reverse will return null.
    How could you use this to tell if a tree is a symmetric tree?

    Here is my solution, if a tree is a symmetric tree, its left subtree and its right subtree shoudl be symmetric to each other

    public class Solution {
        public boolean isSymmetricSubTree(TreeNode left, TreeNode right){
            if(left==null&&right==null) return true;
            if(left==null&&right!=null||right==null&&left!=null) return false;
            if(left.val!=right.val) return false;
                return isSymmetricSubTree(left.left, right.right)&&isSymmetricSubTree(left.right,right.left);
        public boolean isSymmetric(TreeNode root) {
            if(root==null) return true;
            return isSymmetricSubTree(root.left,root.right);

  • 0

    for this code: if(tmp == root)

    I think you want to compare the val of leave nodes, but you are actually compare two addresses.

Log in to reply

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