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. public class Solution {
  4. public boolean isSymmetric(TreeNode root) {
  5. if (root == null) return true;
  6. return isSymmetric(root.left, root.right);
  7. }
  8. private static boolean isSymmetric(TreeNode p, TreeNode q) {
  9. if (p == null && q == null) return true; // 终止条件
  10. if (p == null || q == null) return false; // 终止条件
  11. return p.val == q.val // 三方合并
  12. && isSymmetric(p.left, q.right)
  13. && isSymmetric(p.right, q.left);
  14. }
  15. }

迭代版

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

相关题目

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