0101.cpp (797B)
1 class Solution { 2 string preorder(TreeNode *root, bool left) { 3 if (!root) return ""; 4 5 string res; 6 stack<TreeNode *> st; 7 st.push(root); 8 while (!st.empty()) { 9 TreeNode *root = st.top(); 10 st.pop(); 11 if (!root) { 12 res += "-"; 13 continue; 14 } 15 res += root->val; 16 if (left) { 17 st.push(root->right); 18 st.push(root->left); 19 } else { 20 st.push(root->left); 21 st.push(root->right); 22 } 23 } 24 return res; 25 } 26 27 public: 28 bool isSymmetric(TreeNode *root) { 29 if (!root) return false; 30 31 return preorder(root->left, true) == preorder(root->right, false); 32 } 33 };