It said it will output false when the input is {1, 2, 2}. but why..?


  • 0
    J

    class Solution {
    public:
    bool isSymmetric(TreeNode *root) {
    if (root == NULL)
    return true;

        return symmetric(root->left, root->right);
            
    }
    
    bool symmetric(TreeNode *left, TreeNode *right){
        
        if (left != right)
            return false;
            
        if (left == NULL&& right == NULL)
            return true;
            
        if (symmetric(left->right, right->left) == false)
            return false;
        if (symmetric(left->left, right->right) == false)
            return false;
            
        return true;
    }
    

    };


  • 1
    Z

    here is my solution in Java version. similar with your code and the reason that the return value is false because of if (left != right) return false; is not the correct determing condition. left must be different with right for they are different TreeNode (even if the values are same).
    or maybe you are trying to check whether the value of two nodes are equal, if (left.val != right.val)

       public boolean isSymmetric(TreeNode root) {
            if (root == null)
    			return true;
    		return isSym(root.left, root.right);
    	}
    	private boolean isSym(TreeNode left, TreeNode right) {
    		if (left == null && right == null)
    			return true;
    		else if (left == null || right == null)
    			return false;
    		else 
    			return left.val == right.val && isSym(left.left, right.right) && isSym(left.right, right.left);
        }

  • 0
    J

    Thanks! what you comment out is correct. we cannot just compare them by "if (left != true)" which is always false. I check the value instead of it, and now it's accepted.

    Thanks again


Log in to reply
 

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