Posted on 2014-01-11 02:29
Uriel 阅读(87)
评论(0) 编辑 收藏 引用 所属分类:
LeetCode
判断两棵二叉树是否完全一样,直接两棵树同时遍历,如果遇到某个节点不同就返回false就行
1 /**
2 * Definition for binary tree
3 * struct TreeNode {
4 * int val;
5 * TreeNode *left;
6 * TreeNode *right;
7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8 * };
9 */
10 class Solution {
11 public:
12 queue<TreeNode *> que;
13 vector<int> lst;
14 bool ok;
15
16 void jge(TreeNode *r1, TreeNode *r2) {
17 if(r1->val != r2->val) ok = false;
18 if(r1->left == NULL && r2->left != NULL) {
19 ok = false;
20 }
21 else if(r1->left != NULL && r2->left == NULL) {
22 ok = false;
23 }
24 else if(r1->left != NULL && r2->left != NULL) {
25 jge(r1->left, r2->left);
26 }
27 if(r1->val != r2->val) ok = false;
28 if(r1->right == NULL && r2->right != NULL) {
29 ok = false;
30 }
31 else if(r1->right != NULL && r2->right == NULL) {
32 ok = false;
33 }
34 else if(r1->right != NULL && r2->right != NULL) {
35 jge(r1->right, r2->right);
36 }
37 }
38
39 bool isSameTree(TreeNode *p, TreeNode *q) {
40 ok = true;
41 if(p == NULL && q == NULL) return true;
42 else if(p == NULL || q == NULL) return false;
43 else
44 jge(p, q);
45 return ok;
46 }
47 };