題目:
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1 / 2 2 / / 3 4 4 3
But the following is not:
1 / 2 2 3 3解答:
最開始非常腦殘地希望補全二叉樹,然後利用1,2,4,8個節點之間的關系來比較。結果越來越復雜。
還是那句話:碰上樹,能遞歸就遞歸,不能遞歸就棧、隊列。這次的遞歸要點:某節點的左子樹的左子樹 = 右子樹的右子樹,左子樹的右子樹 = 右子樹的左子樹。
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool compare(TreeNode* left, TreeNode* right) { if (!left && !right) return true; if((!left && right) || (left && !right) || (left->val != right->val)) return false; return compare(left->left, right->right) && compare(left->right, right->left); } bool isSymmetric(TreeNode* root) { if (root == NULL || (!root->left && !root->right)) return true; else return compare(root->left, root->right); } };