Symmetric Tree [LEETCODE]
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
Note:
Bonus points if you could solve it both recursively and iteratively.
confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.
OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
1
/ \
2 3
/
4
\
5
The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".First I thought this problem could be solved by a pre-order traverse of the tree. Then I found I was wrong. The following tree will generate a list like "{2,3,1,2,3}", which is symmetric while the tree is not.
1 / \ 2 2 \ \ 3 3
Then the serialization of tree enlightened me. The mark "#" could be used to represent a NULL child. Why couldn't I use it too? So I got the following tree which generates a list as "{#,2,3,1,#,2,3}" when practice a pre-order tarverse.
Apparently the list is not symmetric any more.
1 / \ 2 2 / \ / \ # 3 # 3
I use a vector<int *> to store pre-order tarverse of the tree, then I can store "#" as a NULL pointer. Here's the code:
1 /** 2 * Definition for binary tree 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 #include <sstream> 11 class Solution { 12 public: 13 bool isSymmetric(TreeNode *root) { 14 // Note: The Solution object is instantiated only once and is reused by each test case. 15 if(NULL == root) return true; 16 vector<int*> vec = treeToVec(root); 17 for(int i = 0; i < vec.size() - 1 - i; i++) { 18 if(NULL == vec[i] && NULL == vec[vec.size()- 1 - i] || 19 NULL != vec[i] && NULL != vec[vec.size()- 1 - i] && *(vec[i]) == *(vec[vec.size()- 1 - i])) { 20 continue; 21 } 22 return false; 23 } 24 return true; 25 26 } 27 vector<int*> treeToVec(TreeNode *root) { 28 vector<int*> result; 29 if(NULL == root) { 30 result.push_back(NULL); 31 return result; 32 } 33 34 vector<int*> left_vec = treeToVec(root->left); 35 vector<int*> right_vec = treeToVec(root->right); 36 for(int i = 0; i < left_vec.size(); i++) { 37 result.push_back(left_vec[i]); 38 } 39 result.push_back(&(root->val)); 40 for(int i = 0; i < right_vec.size(); i++) { 41 result.push_back(right_vec[i]); 42 } 43 return result; 44 } 45 };

浙公网安备 33010602011771号