
判断两棵树是否相同(结构相同,对应的数值相同)
link
显然,这道题可以用DFS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
* Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool (TreeNode* p, TreeNode* q) { if(p == NULL && q == NULL) return true; if(p == NULL || q == NULL) return false; return (p->val==q->val) && isSameTree(p->left, q->left) && isSameTree(p->right, q->right); } };
|
这道题第二种解法可以用宽度优先搜索(BFS),此处用栈代替队列
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
stack<TreeNode*> stack_p; stack<TreeNode*> stack_q; if(p) stack_p.push(p); if(q) stack_q.push(q); while(!stack_p.empty() && !stack_q.empty()){ TreeNode* cur_p=stack_p.top(); TreeNode* cur_q=stack_q.top(); stack_p.pop(); stack_q.pop(); if(cur_p->val!=cur_q->val) return false; if(cur_p->left) stack_p.push(cur_p->left); if(cur_q->left) stack_q.push(cur_q->left); if(stack_p.size() != stack_q.size()) return false; if(cur_p->right) stack_p.push(cur_p->right); if(cur_q->right) stack_q.push(cur_q->right); if(stack_p.size() != stack_q.size()) return false; } return stack_p.size() == stack_q.size();
|
近期评论