Symmetric Tree

描述

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

  1. 1
  2. / \
  3. 2 2
  4. / \ / \
  5. 3 4 4 3

But the following [1,2,2,null,3,null,3] is not:

  1. 1
  2. / \
  3. 2 2
  4. \ \
  5. 3 3

Note:Bonus points if you could solve it both recursively and iteratively.

分析

递归版

  1. // Symmetric Tree
  2. // 递归版,时间复杂度O(n),空间复杂度O(logn)
  3. class Solution {
  4. public:
  5. bool isSymmetric(TreeNode *root) {
  6. if (root == nullptr) return true;
  7. return isSymmetric(root->left, root->right);
  8. }
  9. bool isSymmetric(TreeNode *p, TreeNode *q) {
  10. if (p == nullptr && q == nullptr) return true; // 终止条件
  11. if (p == nullptr || q == nullptr) return false; // 终止条件
  12. return p->val == q->val // 三方合并
  13. && isSymmetric(p->left, q->right)
  14. && isSymmetric(p->right, q->left);
  15. }
  16. };

迭代版

  1. // Symmetric Tree
  2. // 迭代版,时间复杂度O(n),空间复杂度O(logn)
  3. class Solution {
  4. public:
  5. bool isSymmetric (TreeNode* root) {
  6. if (!root) return true;
  7. stack<TreeNode*> s;
  8. s.push(root->left);
  9. s.push(root->right);
  10. while (!s.empty ()) {
  11. auto p = s.top (); s.pop();
  12. auto q = s.top (); s.pop();
  13. if (!p && !q) continue;
  14. if (!p || !q) return false;
  15. if (p->val != q->val) return false;
  16. s.push(p->left);
  17. s.push(q->right);
  18. s.push(p->right);
  19. s.push(q->left);
  20. }
  21. return true;
  22. }
  23. };

相关题目

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/cpp/binary-tree/traversal/symmetric-tree.html