LeetCode 100. Same Tree C语言
2016-04-24 20:55
423 查看
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.
树的问题最容易想到的是用递归;
一颗二叉树相同是它的根节点相同和左右子树相同;
左右子树是否相同也一样这样想;
特殊情况是两棵树都为空,还有其中一棵树为空;
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
bool isSameTree(struct TreeNode* p, struct 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);
}
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
树的问题最容易想到的是用递归;
一颗二叉树相同是它的根节点相同和左右子树相同;
左右子树是否相同也一样这样想;
特殊情况是两棵树都为空,还有其中一棵树为空;
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
bool isSameTree(struct TreeNode* p, struct 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);
}
相关文章推荐
- 深入浅出--C\C++指针的本质
- C++中static_cast/const_cast/dynamic_cast/reinterpret_cast的区别和使用
- C++ 学习基础篇(一)—— C++与C 的区别
- C++中static_cast/const_cast/dynamic_cast/reinterpret_cast的区别和使用
- 文章标题 c语言中关于串的相关知识以及操作
- LeetCode 283. Move Zeroes C语言
- C++走向远洋——38(用对象数组操作长方柱类)
- C++学习(二)——指针与动态内存分配
- LeetCode 226. Invert Binary Tree C语言
- C++第4次作业
- C语言
- LeetCode 104. Maximum Depth of Binary Tree C语言
- C++的4种类型转换关键字及其特点
- c++实现4阶矩阵或行列式的计算
- LeetCode 258. Add Digits C语言
- C语言指针高级七
- LeetCode 292. Nim Game C语言
- C语言数组三
- c语言基础深入理解二
- c语言深入理解基本概念