100.Same Tree
Given the roots of two binary trees p
and q
, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.
Example 1:
1 2
| Input: p = [1,2,3], q = [1,2,3] Output: true
|
Example 2:
1 2
| Input: p = [1,2], q = [1,null,2] Output: false
|
Example 3:
1 2
| Input: p = [1,2,1], q = [1,1,2] Output: false
|
深度优先搜索:
时间复杂度:O(min(m,n))
空间复杂度:O(min(m,n))
1 2 3 4 5 6 7 8 9 10 11
| bool isSameTree(TreeNode* p, TreeNode* q) { if (p == nullptr && q == nullptr) { return true; } else if (p == nullptr || q == nullptr) { return false; } else if (p->val != q->val) { return false; } else { return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); } }
|
广度优先搜索:
时间复杂度:O(min(m,n))
空间复杂度:O(min(m,n))
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| bool isSameTree(TreeNode* p, TreeNode* q) { if (p == nullptr && q == nullptr) { return true; } else if (p == nullptr || q == nullptr) { return false; } queue <TreeNode*> queue1, queue2; queue1.push(p); queue2.push(q); while (!queue1.empty() && !queue2.empty()) { auto node1 = queue1.front(); queue1.pop(); auto node2 = queue2.front(); queue2.pop(); if (node1->val != node2->val) { return false; } auto left1 = node1->left, right1 = node1->right, left2 = node2->left, right2 = node2->right; if ((left1 == nullptr) ^ (left2 == nullptr)) { return false; } if ((right1 == nullptr) ^ (right2 == nullptr)) { return false; } if (left1 != nullptr) { queue1.push(left1); } if (right1 != nullptr) { queue1.push(right1); } if (left2 != nullptr) { queue2.push(left2); } if (right2 != nullptr) { queue2.push(right2); } } return queue1.empty() && queue2.empty(); }
|