http://oj.leetcode.com/problems/symmetric-tree/
判断树是否对称
class Solution { public: bool compare(TreeNode *left, TreeNode *right) { if(left == NULL && right != NULL) return false; if(left != NULL && right == NULL) return false; if(left == NULL && right == NULL) return true; if(left->val != right->val) return false; return compare(left->left, right->right) && compare(left->right, right->left); } bool isSymmetric(TreeNode *root) { if(root == NULL) return true; return compare(root->left, root->right); } };
上面是卡哒的代码。
本来想的是中序遍历,然后判断是否回文。代码如下:
struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; vector<char> ans; void leftFirstTravel(TreeNode *root) { if(root->left == NULL) ans.push_back('#'); else leftFirstTravel(root->left); ans.push_back(root->val); if(root->right == NULL) ans.push_back('#'); else leftFirstTravel(root->right); return; } class Solution { public: bool isSymmetric(TreeNode *root) { if(root == NULL) return true; ans.clear(); leftFirstTravel(root); int size = ans.size(); int mid = size/2; for(int i = 1;mid - i>= 0;i++) { if(ans[mid-i] != ans[mid+i] ) return false; } return true; } };
Input: | {1,2,3,3,#,2,#} |
Output: | true |
Expected: | false |
但是这样遍历出来的是 3 2 1 2 3 即便是加了#,是# 3 # 2 # 1 # 2 # 3 # ,但实际上不是。嗯嗯,要更加深刻的理解递归。