LeetCode 101. Symmetric Tree
题目:判断一棵树的左子树和右子树是否对称。
解题思路:
- 递归判断,对于每一棵非空树,如果左子树不与右子树对称,那么整棵树就不满足对称性。
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 bool isSymmetric2(TreeNode* left,TreeNode* right){ 13 if(left==NULL && right==NULL){ 14 return true; 15 } 16 else if(left==NULL || right==NULL){ 17 return false; 18 } 19 else if(left->val==right->val && isSymmetric2(left->left,right->right) && isSymmetric2(left->right,right->left)){ 20 return true; 21 } 22 return false; 23 } 24 25 bool isSymmetric(TreeNode* root) { 26 if(root==NULL){ 27 return true; 28 } 29 return isSymmetric2(root->left,root->right); 30 } 31 }; 32