题意:

image.png

解题思路:

  1. 思路:
  2. 递归:O(n)
  3. 1. 首先判断t1->val == t2->val
  4. 2. 再判断,t1->left->val == t2->right->val, t1->right->val == t2->left->val
  5. 3. 终止条件为两棵树中一颗为空,或者已经到达了空节点;
  6. BFS:采用队列来实现,思路跟递归差不多;时间复杂度是 O(n)
  7. 1. 先将根的左右节点入队
  8. 2. 弹出左右节点进行比较;如果相等,则将t1->left t2->right放入对列;
  9. 3. 再将t1->right t2->left 放入队列;
  10. 4. 继续下一轮比较,直到子树为空退出;

PHP代码实现:

  1. class Solution {
  2. /**
  3. * @param TreeNode $root
  4. * @return Boolean
  5. */
  6. function isSymmetric($root) {
  7. return $this->isSymmetricIterative($root);
  8. // return $this->isMirror($root, $root);
  9. }
  10. function isMirror($t1, $t2) {
  11. if ($t1 == null && $t2 == null) return true;
  12. if ($t1 == null || $t2 == null) return false;
  13. return $t1->val == $t2->val && $this->isMirror($t1->left, $t2->right) &&
  14. $this->isMirror($t1->right, $t2->left);
  15. }
  16. function isSymmetricIterative($root) {
  17. if ($root == null) return true;
  18. $s = new SplStack;
  19. $s->push($root->left);
  20. $s->push($root->right);
  21. while (!$s->isEmpty()) {
  22. $s1 = $s->pop();
  23. $s2 = $s->pop();
  24. if ($s1 == null && $s2 == null) continue;
  25. if ($s1 == null || $s2 == null) return false;
  26. if ($s1->val != $s2->val) return false;
  27. $s->push($s1->left);
  28. $s->push($s2->right);
  29. $s->push($s1->right);
  30. $s->push($s2->left);
  31. }
  32. return true;
  33. }
  34. }

GO代码实现:

  1. /**
  2. * Definition for a binary tree node.
  3. * type TreeNode struct {
  4. * Val int
  5. * Left *TreeNode
  6. * Right *TreeNode
  7. * }
  8. */
  9. func isSymmetric(root *TreeNode) bool {
  10. if root == nil {
  11. return true
  12. }
  13. return isMirror(root, root)
  14. }
  15. func isMirror(left, right *TreeNode) bool {
  16. if left == nil && right == nil {
  17. return true
  18. }
  19. if left == nil || right == nil {
  20. return false
  21. }
  22. return left.Val == right.Val && isMirror(left.Left, right.Right) && isMirror(left.Right, right.Left)
  23. }
  24. func isMirrorIterate(left, right *TreeNode) bool {
  25. q := []*TreeNode{}
  26. q = append(q, left, right)
  27. for len(q) > 0 {
  28. n1, n2 := q[0], q[1]
  29. q = q[2:]
  30. if n1 == nil && n2 == nil {
  31. continue
  32. }
  33. if n1 == nil || n2 == nil {
  34. return false
  35. }
  36. if n1.Val != n2.Val {
  37. return false
  38. }
  39. q = append(q, n1.Left, n2.Right)
  40. q = append(q, n1.Right, n2.Left)
  41. }
  42. return true
  43. }