엔지니어 게시판
LeetCode 솔루션 분류

[Easy - wk4 - Q2] 101. Symmetric Tree

컨텐츠 정보

본문

101. Symmetric Tree 


Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).

 

Example 1:

Input: root = [1,2,2,3,4,4,3]
Output: true

Example 2:

Input: root = [1,2,2,null,3,null,3]
Output: false

 

Constraints:

  • The number of nodes in the tree is in the range [1, 1000].
  • -100 <= Node.val <= 100

 

Follow up: Could you solve it both recursively and iteratively? 

관련자료

댓글 2

mingki님의 댓글

  • 익명
  • 작성일
C++
Runtime: 14 ms, faster than 13.66% of C++ online submissions for Symmetric Tree.
Memory Usage: 16.3 MB, less than 93.41% of C++ online submissions for Symmetric Tree.
class Solution {
    bool helper(TreeNode *left, TreeNode *right) {
        if (!left && !right) return true;
        if (!left || !right) return false;
        return left->val == right->val &&
               helper(left->left, right->right) &&
               helper(left->right, right->left);
    }
    
public:
    bool isSymmetric(TreeNode *root) {
        return helper(root, root);
    }
};

dawn27님의 댓글

  • 익명
  • 작성일
JS
Runtime: 77 ms, faster than 79.08% of JavaScript online submissions for Symmetric Tree.
Memory Usage: 44.3 MB, less than 85.73% of JavaScript online submissions for Symmetric Tree.

var isSymmetric = function(root) {
  if (root === null) {
    return true;
  }

  return isMirror(root.left, root.right);
}
var isMirror = function(tree1, tree2) {
  if (tree1 === null || tree2 === null) {
    return tree1 === tree2;
  }

  if (tree1.val !== tree2.val) {
    return false;
  }

  return isMirror(tree1.left, tree2.right) && isMirror(tree1.right, tree2.left);
};
전체 404 / 1 페이지
번호
제목
이름

최근글


인기글


새댓글


Stats


알림 0