Same Tree

描述

Given two binary trees, write a function to check if they are equal or not.

Two binary trees are considered equal if they are structurally identical and the nodes have the same value.

分析

递归版

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

迭代版

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

相关题目

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