[leetcode] 100. Same Tree

来源:互联网 发布:java从右截取字符串 编辑:程序博客网 时间:2024/04/29 07:46

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

Two binary trees are considered equal if they are structurally identical and the nodes have the same value.

这道题是判断两个二叉树是否相同,题目难度为Easy。

从根节点开始判断,如果节点值相等按同样的方法向两个子节点判断,如果不等返回false,这样通过递归即可完成判断,具体代码:

class Solution {public:    bool isSameTree(TreeNode* p, TreeNode* q) {        if(!p && !q) return true;        if(p && q && p->val == q->val)            return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);        else             return false;    }};
另外还可以按照遍历二叉树的思路进行判重,方法比较多,这里就不详细列出来了,感兴趣的同学可以看下遍历二叉树的题目。
0 0
原创粉丝点击