Same Tree
2016-03-01 22:11
246 查看
题目:
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.
比较两个二叉树是否相同,简单一些的就可以使用递归,如果对性能有要求的话,可以使用迭代。下面是实际代码,
递归:
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. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public boolean isSameTree(TreeNode p, TreeNode q) { if(p == null && q == null) return true; if(p != null && q != null){ if(p.val != q.val) return false; return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); } else return false; } }
相关文章推荐
- D5
- 创建一个学生类,按照要求生成各种方法,然后使用数学方法计算某一个元素的规定结果
- 如何实现动态规划?——TWO
- CSS---!important
- MyEclipse使用总结——MyEclipse去除网上复制下来的来代码带有的行号
- 使用Core Animation对象来实现动画
- 使用Core Animation对象来实现动画
- ♥POJ 3278-Catch That Cow【搜索】
- 项链
- cocos2d-x之文件读写
- Codeforces Round #259 (Div. 2) B. Little Pony and Sort by Shift
- C++利用函数调用实现数组数据的输入输出
- Android中使用Activity的权限进行启动验证
- 运算符重载
- 32位机和64位机下面各类型sizeof的大小
- MyEclipse使用总结——MyEclipse10安装SVN插件
- win7所有服务被禁用(应该是大多数被禁用)
- 配置struts2的默认后缀
- 【小笔记】afnetworking取数据时输入接口地址
- 斐波拉契快速求法:矩阵快速幂