Java symmetric tree solution


  • 0
    V

    same idea with No.100 : same tree.

    public class Solution {

    public boolean isSymmetric(TreeNode root) {
    
        if(root == null){
            return true;
        }
        
        if(root.left == null && root.right != null){
            return false;
        }
        if(root.left != null && root.right == null){
            return false;
        }
        
        return symmetric(root.left, root.right);
    }
    
    private boolean symmetric(TreeNode x, TreeNode y){
    
        if(x == null && y == null){
            return true;
        }
        if(x == null && y != null){
            return false;
        }
        if(x != null && y == null){
            return false;
        }
        if(x.val != y.val){
            return false;
        }
        
        return symmetric(x.left, y.right) && symmetric(x.right, y.left);
    }
    

    }


Log in to reply
 

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