Same Tree
来源:互联网 发布:易语言注入dll源码 编辑:程序博客网 时间:2024/06/01 10:38
题目:
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.
思路:递归解决,根节点及左右子树递归下去都要相等,只要有一个不等显然就不等,所以用&&运算符连接,还有注意两者都为null返回true,一个null一个不为null返回false,代码如下:
/** * 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; } else { if(p == null || q == null) { return false; } else { return p.val == q.val && isSameTree(p.left,q.left) && isSameTree(p.right,q.right); } } }}
0 0
- Same Tree
- Same Tree
- Same Tree
- Same Tree
- Same Tree
- Same Tree
- Same Tree
- Same Tree
- Same Tree
- Same Tree
- Same tree
- Same Tree
- Same Tree
- Same Tree
- Same Tree
- Same Tree
- Same Tree
- Same Tree
- Linux 下安装配置 JDK
- 年终_01
- 年终总结
- Java之旅
- JAVA Linux 排查CPU 过高的方法
- Same Tree
- VIM相关问题
- 跨年快乐
- 代码规范文档
- 解决Ubuntu14.04中VMware workstaion无法打开
- C语言中函数的参数列表为空和void的区别
- C语言写的工具箱
- centos6.5 下配置vnc(转有删改)
- 【笔记】Linux文件处理