Given two binary trees, write a function to check if they are the same or not.

Two binary trees are considered the same if they are structurally identical and the nodes have the same value. (0ms)

采用递归先根遍历即可。 

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     struct TreeNode *left;
 6  *     struct TreeNode *right;
 7  * };
 8  */
 9 
10 bool pre_traverse(struct TreeNode *p,struct TreeNode *q)
11 {
12     if(!p && !q) return true;
13     if((p && !q) || (!p && q) ||(p->val != q->val)) return false;
14     if(!pre_traverse(p->left,q->left)) return false;
15     if(!pre_traverse(p->right,q->right)) return false;
16     
17     return true;
18 }
19 bool isSameTree(struct TreeNode* p, struct TreeNode* q) {
20     return pre_traverse(p,q);
21 }

 

posted on 2018-03-14 22:29  gtxvs  阅读(110)  评论(0编辑  收藏  举报