確認樹是不是對稱鏡像的
感覺要一路Traversal到底部,並且同時對樹的分支做。
class Solution {
public:
bool isSymmetric(TreeNode* root) {
return isMirror(root->left, root->right);
}
bool isMirror(TreeNode* nodeA, TreeNode* nodeB) {
if (nodeA == NULL && nodeB == NULL)
return true;
if (nodeA == NULL || nodeB == NULL)
return false;
if (nodeA->val == nodeB->val)
return isMirror(nodeA->left, nodeB->right) && isMirror(nodeA->right, nodeB->left);
return false;
}
};
參考:
https://www.geeksforgeeks.org/symmetric-tree-tree-which-is-mirror-image-of-itself/