您的位置:首页 > 其它

【LeetCode】100. Same Tree 解题报告

2018-03-04 13:06 399 查看
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.

Example1:

Input:     1         1
/ \       / \
2   3     2   3

[1,2,3],   [1,2,3]

Output: true


Example2:

Input:     1         1
/           \
2             2

[1,2],     [1,null,2]

Output: false


Example3:

Input:     1         1
/ \       / \
2   1     1   2

[1,2,1],   [1,1,2]

Output: false


算法思路:该题的解法就是比较树的结构和内容是否一致,可以采用前序遍历,中序遍历,后序遍历。

/**
* 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 isSameTree(TreeNode* p, TreeNode* q) {
if(!p&&!q)return true;
if(!p||!q)return false;
return p->val==q->val&&isSameTree(p->left,q->left)&&isSameTree(p->right,q->right);
}
};


/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSameTree(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);
}
}


该题为简单题
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: