Skip to content

Commit c1b60a6

Browse files
authored
100. Same Tree BFS Problem in C++ (#181)
* BFS LeetCode problem 100 in C++ * Delete 100_Same_Tree.cpp * BFS LeetCode problem 100 in C++
1 parent 5c2c330 commit c1b60a6

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

Diff for: C++/100_Same_Tree.cpp

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
8+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10+
* };
11+
*/
12+
class Solution {
13+
public:
14+
bool isSameTree(TreeNode* p, TreeNode* q) {
15+
if(p == nullptr && q == nullptr)
16+
return true;
17+
if(p == nullptr || q == nullptr)
18+
return false;
19+
if(p->val != q->val) return false;
20+
21+
return (isSameTree(p->right,q->right) && isSameTree(p->left, q->left));
22+
}
23+
};
24+
25+
// Complexity Analysis:
26+
// Time complexity : O(N), where N is a number of nodes in the tree, since one visits each node exactly once.
27+
// Space complexity :O(log(N)) in the best case of completely balanced tree and O(N) in the worst case of completely unbalanced tree.

0 commit comments

Comments
 (0)