原题:
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 binary tree
* 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) {
// Note: The Solution object is instantiated only once and is reused by each test case.
}
};
晓东分析:
其实两个二叉树是否相同的判断,看起来还是蛮简单的,若用递归实现的话,就是要左,右节点作为根节点的二叉树是都是相同的,且val也要是相同的即可。
只是需要考虑几个特殊情况,比如左右节点一个是null一个不是这样的情况。
代码实现:
/**
* Definition for binary tree
* 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) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(p == NULL && q == NULL) return true;
if(!(p != NULL && q != NULL)) return false;
bool left_result = isSameTree(p->left, q->left);
bool right_result = isSameTree(p->right, q->right);
bool value_result = p->val == q->val;
return (left_result == true && right_result == true && value_result == true)? true: false;
}
};
执行结果:
52 / 52test cases passed.
|
Status:
Accepted
|
Runtime: 16 ms
|
希望大家有更好的算法能够提出来,不甚感谢。
若您觉得该文章对您有帮助,请在下面用鼠标轻轻按一下“顶”,哈哈~~·
分享到:
相关推荐
/*选择二叉链式存储结构作为二叉树的存储结构,设计一个程序实现二叉树的基本操作(包括建立、输出、前序遍历、中序遍历、后序遍历、求树高、统计叶子总数等) 【实验内容】 必做内容 程序的菜单功能项如下: 1----...
java 从上到下打印二叉树java 从上到下打印二叉树
二叉树遍历问题 二叉树遍历问题-前序, 中序, 后序二叉树遍历问题-前序, 中序, 后序二叉树遍历问题-前序, 中序, 后序二叉树遍历问题-前序, 中序, 后序二叉树遍历问题-前序, 中序, 后序二叉树遍历问题-前序...
使用非递归算法遍历二叉树,在屏幕上打印出二叉树中序遍历序列。
【源码】【数据结构几个实例】【约瑟夫环问题--停车场管理--二叉树的建立与遍历--图遍历--哈希表设计】
算法-理论基础- 二叉树- 二叉树的遍历(包含源程序).rar
template<class Type> class BinaryTree; template<class Type> class BinTreeNode { friend class BinaryTree; private: BinTreeNode<Type> *leftChild,*rightChild; Type data; public: BinTreeNode():...
本程序简单实现了《数据结构》课本中二叉树的中序线索化算法,并同时实现了与子对应的中序线索化非递归遍历二叉树的算法
数据结构二叉树,内含有代码,还不错!!!!!!!
简洁的二叉树编码 简洁地表示二叉树的结构 例子 将二叉树编码为位字段: var succinct = require ( 'succinct-binary-tree-encoding' ) var tree = JSON . parse ( process . argv . slice ( 2 ) . join ( ' ' ) ) ...
二叉树类及其实现以二叉链表为存储结构实现二叉树类和成员函数, 设计计算二叉树结点、将二叉树每个结点的左右子树交换、求二叉树高度的算法
开发环境 VS2019 由于C语言中没有引用 (&),所以这里使用的是C++,极大程度还原了课本中的代码。 若有不足,请批评指正!! 谢谢!!!...BinaryTree------二叉树 BiThrTree-------线索二叉树
利用Hull-White模型对油价波动进行预测是一种有意义的尝试, 在尝试过程中, 发现其在实际应用中的缺陷, 之后利用二叉树模型对Hull-White模型做了改进, 并以1986年1月3日至2010年2月12日共一千两百多周的周油价数据...
二叉树的左遍历优先:有详细的说明,希望对你有帮助。
题目二叉树所有路径题解* Definition for a binary tree node.* function TreeNode(val) {* @para
大数据-算法-投资组合风险与期权二叉树.pdf
二叉树的定义、二叉树的前序、中序与后续的遍历代码实现
数据结构-第六章 树和二叉树.ppt
二叉树遍历 React App会显示遍历,例如二叉树的有序,前序,后序和广度优先遍历。 建立在ReactJs之上 设置步骤: git clone cd BinaryTree遍历 npm安装 npm开始 浏览到htpp:// localhost:3000 登陆页面 包含一...