101. Symmetric Tree
給定一個二元樹的根節點,檢查它是否是自身的鏡像(即,關於其中心對稱)。
範例:
輸入:root = [1,2,2,3,4,4,3] 輸出:true
這表明給定的二元樹在其中心線上是對稱的,因為樹的左側和右側完全相同。
Python
class Solution:
def isSymmetric(self, root: Optional[TreeNode]) -> bool:
if not root:
return True
def isMirror(left: Optional[TreeNode], right: Optional[TreeNode]) -> bool:
# If both nodes are None, they're symmetric
if not left and not right:
return True
# If one node is None and the other isn't, they're not symmetric
if not left or not right:
return False
# Check if the values are the same and if subtrees are mirrors
return (left.val == right.val) and \
isMirror(left.left, right.right) and \
isMirror(left.right, right.left)
# Start the comparison with the left and right subtrees of the root
return isMirror(root.left, root.right)
16.49MB, 36ms
C++
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if (root == nullptr) return true; // A null tree is symmetric
return isMirror(root->left, root->right);
}
private:
bool isMirror(TreeNode* left, TreeNode* right) {
if (left == nullptr && right == nullptr) {
return true; // Both subtrees are null, so they are mirrors
}
if (left == nullptr || right == nullptr) {
return false; // Only one subtree is null, so they are not mirrors
}
// Check if the current nodes have the same value and the subtrees are mirrors of each other
return (left->val == right->val)
&& isMirror(left->left, right->right)
&& isMirror(left->right, right->left);
}
};
17.18MB, 5ms
Javascript
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {boolean}
*/
var isSymmetric = function(root) {
if (!root) {
return true; // An empty tree is symmetric
}
return isMirror(root.left, root.right);
};
function isMirror(tree1, tree2) {
if (!tree1 && !tree2) {
return true; // Both trees are null, thus symmetric
}
if (!tree1 || !tree2) {
return false; // If only one is null, they can't be symmetric
}
// Check if current nodes are equal and subtrees are mirrors of each other
return (tree1.val === tree2.val)
&& isMirror(tree1.left, tree2.right)
&& isMirror(tree1.right, tree2.left);
}
52.2MB, 50ms