力扣 题目100- 相同的树
题目
题解
使用力扣 题目94- 二叉树的中序遍历 的遍历方法对两个二叉树同时遍历 在遍历的同时对结构与值判断
代码
使用两个容器
1 #include<iostream> 2 #include<stack> 3 using namespace std; 4 5 struct TreeNode { 6 int val; 7 TreeNode *left; 8 TreeNode *right; 9 TreeNode() : val(0), left(nullptr), right(nullptr) {} 10 TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 11 TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 12 }; 13 14 class Solution { 15 public: 16 bool isSameTree(TreeNode* p, TreeNode* q) { 17 stack<TreeNode*> ergodic_p; 18 stack<TreeNode*> ergodic_q; 19 while ((p != nullptr||q != nullptr) || (!ergodic_p.empty() && !ergodic_q.empty())) { 20 if (p != nullptr&&q != nullptr) { 21 ergodic_p.push(p); 22 ergodic_q.push(q); 23 p = p->left; 24 q = q->left; 25 } 26 else if (p == nullptr && q == nullptr &&ergodic_p.top()->val== ergodic_q.top()->val) 27 { 28 p = ergodic_p.top()->right; 29 q = ergodic_q.top()->right; 30 ergodic_p.pop(); 31 ergodic_q.pop(); 32 } 33 else 34 { 35 return 0; 36 } 37 } 38 return 1; 39 } 40 }; 41 42 int main() { 43 Solution sol; 44 TreeNode* head2 = new TreeNode(2); 45 TreeNode* head3 = new TreeNode(3); 46 TreeNode* p = new TreeNode(1, head2, head3); 47 TreeNode* q = new TreeNode(1, head3, head2); 48 int result=sol.isSameTree(p,q); 49 cout << result << endl; 50 }
使用一个容器
1 #include<iostream> 2 #include<stack> 3 using namespace std; 4 5 struct TreeNode { 6 int val; 7 TreeNode *left; 8 TreeNode *right; 9 TreeNode() : val(0), left(nullptr), right(nullptr) {} 10 TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 11 TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 12 }; 13 14 class Solution { 15 public: 16 bool isSameTree(TreeNode* p, TreeNode* q) { 17 stack<TreeNode*> ergodic; 18 while ((p != nullptr||q != nullptr) || !ergodic.empty()) { 19 if (p != nullptr&&q != nullptr) { 20 ergodic.push(p); 21 ergodic.push(q); 22 p = p->left; 23 q = q->left; 24 } 25 else if (p == nullptr && q == nullptr) 26 { 27 int last = ergodic.top()->val; 28 p = ergodic.top()->right; 29 ergodic.pop(); 30 if (last== ergodic.top()->val) { 31 q = ergodic.top()->right; 32 ergodic.pop(); 33 } 34 else 35 { 36 return 0; 37 } 38 } 39 else 40 { 41 return 0; 42 } 43 } 44 return 1; 45 } 46 }; 47 48 int main() { 49 Solution sol; 50 TreeNode* head2 = new TreeNode(2); 51 TreeNode* head3 = new TreeNode(3); 52 TreeNode* p = new TreeNode(1, head2, head3); 53 TreeNode* q = new TreeNode(1, head3, head2); 54 int result=sol.isSameTree(p,q); 55 cout << result << endl; 56 }