题意:

image.png

解题思路:

  1. 思路:[递归+迭代]
  2. 1. 递归判断 p q 是不是 null,如果不是则判断它们的值是否相等,继续递归子节点;
  3. 2. 先入栈根节点,每次迭代将当前结点弹出,然后进行判断;
  4. * p q 非空
  5. * p->val 等于q->val
  6. 3. 满足上面条件,则继续压入两树的左右子结点;

PHP代码实现:

  1. /**
  2. * Definition for a binary tree node.
  3. * class TreeNode {
  4. * public $val = null;
  5. * public $left = null;
  6. * public $right = null;
  7. * function __construct($value) { $this->val = $value; }
  8. * }
  9. */
  10. class Solution {
  11. /**
  12. * @param TreeNode $p
  13. * @param TreeNode $q
  14. * @return Boolean
  15. */
  16. function isSameTree($p, $q) {
  17. if ($p == null && $q == null) return true;
  18. if ($p == null || $q == null) return false;
  19. return $p->val == $q->val
  20. && $this->isSameTree($p->left, $q->left) && $this->isSameTree($p->right, $q->right);
  21. }
  22. function isSameTreeIterative($p, $q) {
  23. $s = new SplStack;
  24. $s->push($p);
  25. $s->push($q);
  26. while (!$s->isEmpty()) {
  27. $s1 = $s->pop();
  28. $s2 = $s->pop();
  29. if ($s1 == null && $s2 == null) continue;
  30. if ($s1 == null || $s2 == null) return false;
  31. if ($s1->val != $s2->val) return false;
  32. $s->push($s1->left);
  33. $s->push($s2->left);
  34. $s->push($s1->right);
  35. $s->push($s2->right);
  36. }
  37. return true;
  38. }
  39. }

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 isSameTree(p *TreeNode, q *TreeNode) bool {
  10. if p == nil && q == nil {
  11. return true
  12. }
  13. if p == nil || q == nil {
  14. return false
  15. }
  16. if p.Val != q.Val {
  17. return false
  18. }
  19. return isSameTree(p.Left, q.Left) && isSameTree(p.Right, q.Right)
  20. }