LeetCode Solutions

101. Symmetric Tree

Time: $O(n)$

Space: $O(h)$

			

class Solution {
 public:
  bool isSymmetric(TreeNode* root) {
    return isSymmetric(root, root);
  }

 private:
  bool isSymmetric(TreeNode* p, TreeNode* q) {
    if (!p || !q)
      return p == q;

    return p->val == q->val &&
           isSymmetric(p->left, q->right) &&
           isSymmetric(p->right, q->left);
  }
};
			

class Solution {
  public boolean isSymmetric(TreeNode root) {
    return isSymmetric(root, root);
  }

  private boolean isSymmetric(TreeNode p, TreeNode q) {
    if (p == null || q == null)
      return p == q;

    return p.val == q.val && isSymmetric(p.left, q.right) && isSymmetric(p.right, q.left);
  }
}
			

class Solution:
  def isSymmetric(self, root: Optional[TreeNode]) -> bool:
    def isSymmetric(p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
      if not p or not q:
        return p == q

      return p.val == q.val and \
          isSymmetric(p.left, q.right) and \
          isSymmetric(p.right, q.left)

    return isSymmetric(root, root)