Same Tree
来源:互联网 发布:如何复制筛选后的数据 编辑:程序博客网 时间:2024/06/06 12:45
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.
思路:给定两个二叉树,判断两棵树的是否是相同的。相同的定义是两棵树的结构相同且在相同位置上的节点val值也相等。
递归的考虑这个问题:
(1)当两棵树的根节点p和q都为NULL的时候,两者结构相同且val相等。
(2)当其中一个为NULL一个不为NULL的时候,两者结构不同,返回false。
(3)当两者都不为NULL的时候,在两者根节点值相等且左右两个子树都是相同的时候,整个原来的两个树是相同的。
对于左右子树的处理也是类似的,因此可以使用递归的方式解决,代码如下所示。
/** * 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==NULL&&q==NULL) return true; if((p&&!q)||(!p&&q)) return false; return p->val==q->val&&isSameTree(p->left,q->left)&&isSameTree(p->right,q->right); }};
0 0
- Same Tree
- Same Tree
- Same Tree
- Same Tree
- Same Tree
- Same Tree
- Same Tree
- Same Tree
- Same Tree
- Same Tree
- Same tree
- Same Tree
- Same Tree
- Same Tree
- Same Tree
- Same Tree
- Same Tree
- Same Tree
- Codeforces Round #355 (Div. 2)C(模拟)
- Sonatype Nexus 搭建Maven 私服
- ABAP 7.4新特性(二):NEW 操作符
- SSL证书种类分析
- ElasticSearch实战-入门
- Same Tree
- JUC源码分析15-集合-ConcurrentHashMap
- 【iOS开发】HTTP请求错误码 ? CodeType
- STM32 OSC_IN跟OSC_OUT的作用 和 各种接法
- 严苛模式(StrictMode)
- 动态添加select2,数据来源本地
- 打通流程管理与MIS数据的管道是运用工作流程工具搭建业务系统的关键
- ios利用正则表达式判断手机号码格式是否正确
- (转载)Qt 的线程与事件循环——可打印threadid进行观察槽函数到底是在哪个线程里执行,学习moveToThread的使用)