Same Tree--比较两个二叉树是否相同
2013-10-27 11:07
399 查看
原题:
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也要是相同的即可。
只是需要考虑几个特殊情况,比如左右节点一个是null一个不是这样的情况。
代码实现:
执行结果:
希望大家有更好的算法能够提出来,不甚感谢。
若您觉得该文章对您有帮助,请在下面用鼠标轻轻按一下“顶”,哈哈~~·
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 |
若您觉得该文章对您有帮助,请在下面用鼠标轻轻按一下“顶”,哈哈~~·
相关文章推荐
- 【二叉树4】比较两个二叉树的结构是否相同
- Same Tree 比较两个二叉树是否完全相同
- 比较两个二叉树是否相同
- 比较两个二叉树是否相同
- same-tree——比较两个二叉树是否相同
- 二叉树(10)----比较两个二叉树是否相同(结构和数据),递归和非递归
- php比较两个字符串是否相同
- perl比较两个目录中的文件内容是否相同
- 重要经验一:比较两个UIImage是否相同
- 比较两个类中使用构造方法传参的值是否相同
- 比较两个ArrayList是否相同
- 比较两个文件是否相同(C/C++语言)
- asm--文件使用--比较两个文件是否内容相同
- C# 比较两个数组中的内容是否相同的算法
- [Swift]判断两个二叉树是否相同
- java比较两个对象(类)是否相同
- 比较两个文件的是否相同
- 比较两个byte数组数据是否相同,相同返回 true
- C#下比较两个等长字符串是否含有完全相同字符(忽略字符顺序)
- 再论:比较两个对象的属性值是否相同 [ 光影人像 东海陈光剑 的博客 ]