Lintcode---等价二叉树
二叉树 --- lintcode 等价
2023-09-14 08:58:39 时间
检查两棵二叉树是否等价。等价的意思是说,首先两棵二叉树必须拥有相同的结构,并且每个对应位置上的节点上的数都相等。
样例
1 1
/ \ / \
2 2 and 2 2
/ /
4 4
就是两棵等价的二叉树。
1 1
/ \ / \
2 3 and 2 3
/ \
4 4
就不是等价的。
思路:
还是用递归的方法,先序遍历二叉树;
当根节点相等时,且左右子树均为等价二叉树时,该二叉树为等价二叉树;
否则,不是等价二叉树;
/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */ class Solution { public: /** * @aaram a, b, the root of binary trees. * @return true if they are identical, or false. */ /* 思路:还是用递归的方法,分情况进行比较; 当根节点相等时,且左右子树均为等价二叉树时,该二叉树为等价二叉树; */ bool isIdentical(TreeNode* a, TreeNode* b) { // Write your code here if(a==NULL&&b==NULL){ return true; } if(a==NULL&&b!=NULL){ return false; } if(a!=NULL&&b==NULL){ return false; } if(a!=NULL&&b!=NULL&&(a->val==b->val)){ if(isIdentical(a->left,b->left)&&isIdentical(a->right,b->right)){ return true; } else{ return false; } } else{ return false; } } };
相关文章
- 二叉树的建立和输出 (层序和递归两种)
- Java实现 LeetCode 623 在二叉树中增加一行(遍历树)
- Java实现 LeetCode 331 验证二叉树的前序序列化
- Lintcode---二叉树的锯齿形层次遍历
- Lintcode---二叉树的最大深度
- Lintcode---克隆二叉树
- Lintcode---二叉树的路径和
- 一文读懂平衡二叉树|技术头条
- 重新整理数据结构与算法(c#)—— 二叉树排序树[二十二]
- 算法练习之相同的树,对称二叉树
- LeetCode-226. 翻转二叉树【递归】
- 二叉树的层序遍历
- 对称二叉树
- LeetCode 101. 对称二叉树
- 【LeetCode】剑指Offer 34.二叉树中和为某一值的路径
- 树形结构——二叉树