leetcode 101. 對稱二叉樹 C語言版
阿新 • • 發佈:2018-11-23
給定一個二叉樹,檢查它是否是映象對稱的。
例如,二叉樹 [1,2,2,3,4,4,3]
是對稱的。
1 / \ 2 2 / \ / \ 3 4 4 3
但是下面這個 [1,2,2,null,3,null,3]
則不是映象對稱的:
1 / \ 2 2 \ \ 3 3
這個題可以用遞迴的方法解決:
bool com(struct TreeNode* a,struct TreeNode* b); bool isSymmetric(struct TreeNode* root) { if(root == NULL) return true; return com(root->left,root->right); } bool com(struct TreeNode* a,struct TreeNode* b) { if(a == NULL&&b == NULL) return true; else { if(a == NULL||b == NULL) return false; else if(a -> val==b -> val) return com(a->left,b->right)&&com(a->right,b->left); else return false; } }