File tree Expand file tree Collapse file tree 2 files changed +58
-5
lines changed Expand file tree Collapse file tree 2 files changed +58
-5
lines changed Original file line number Diff line number Diff line change 7
7
using namespace std ;
8
8
9
9
10
- // / Recursion
10
+ // / Using a string to represent a Binary Tree in preorder
11
11
// / Time Complexity: O(n)
12
12
// / Space Complexity: O(h)
13
13
@@ -23,10 +23,26 @@ class Solution {
23
23
public:
24
24
bool isSameTree (TreeNode* p, TreeNode* q) {
25
25
26
- if (!p && !q) return true ;
27
- if (!p || !q) return false ;
28
- if (p->val != q->val ) return false ;
29
- return isSameTree (p->left , q->left ) && isSameTree (p->right , q->right );
26
+ string ps = " #" ;
27
+ getTreeString (p, ps);
28
+
29
+ string qs = " #" ;
30
+ getTreeString (q, qs);
31
+
32
+ return ps == qs;
33
+ }
34
+
35
+ private:
36
+ void getTreeString (TreeNode* node, string& s){
37
+
38
+ if (!node){
39
+ s += " NULL#" ;
40
+ return ;
41
+ }
42
+
43
+ s += to_string (node->val ) + " #" ;
44
+ getTreeString (node->left , s);
45
+ getTreeString (node->right , s);
30
46
}
31
47
};
32
48
Original file line number Diff line number Diff line change
1
+ // / Source : https://leetcode.com/problems/same-tree/description/
2
+ // / Author : liuyubobobo
3
+ // / Time : 2018-10-16
4
+
5
+ #include < iostream>
6
+
7
+ using namespace std ;
8
+
9
+
10
+ // / Recursion
11
+ // / Time Complexity: O(n)
12
+ // / Space Complexity: O(h)
13
+
14
+ // / Definition for a binary tree node.
15
+ struct TreeNode {
16
+ int val;
17
+ TreeNode *left;
18
+ TreeNode *right;
19
+ TreeNode (int x) : val(x), left(NULL ), right(NULL ) {}
20
+ };
21
+
22
+ class Solution {
23
+ public:
24
+ bool isSameTree (TreeNode* p, TreeNode* q) {
25
+
26
+ if (!p && !q) return true ;
27
+ if (!p || !q) return false ;
28
+ if (p->val != q->val ) return false ;
29
+ return isSameTree (p->left , q->left ) && isSameTree (p->right , q->right );
30
+ }
31
+ };
32
+
33
+
34
+ int main () {
35
+
36
+ return 0 ;
37
+ }
You can’t perform that action at this time.
0 commit comments