LeetCode_SameTree
来源:互联网 发布:域名添加a记录 编辑:程序博客网 时间:2024/06/05 22:45
Total Accepted: 102505 Total Submissions: 241539 Difficulty: Easy
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.
Subscribe to see which companies asked this question
如题,判断两个二叉树是否是相同的:
思路是:判断其节点是否相同,然后再判断其子节点。
public class Solution { public boolean isSameTree(TreeNode p, TreeNode q) { if(p==q){ if(isSameTree(p.left,q.left)&&isSameTree(p.right,q.right)){ return true; } } return false; }}然而这种做法是不对的,因为节点p和q的引用是不同的,所以不能这样判断,造成的结果就是本来是相同的树,也会识别错误。 改正后
还是会报错:
if(p.val==q.val){
Line 14: java.lang.NullPointerException
好吧,空指针错误,于是,public class Solution { public boolean isSameTree(TreeNode p, TreeNode q) { if(p==null && q==null) return true; if(p==null || q==null) return false; if(p.val==q.val){ if(isSameTree(p.left,q.left)&&isSameTree(p.right,q.right)){ return true; } } return false; }}世界安静了!
0 0
- LeetCode_SameTree
- LeetCode_SameTree
- LeetCode__Add Digits
- Leetcode__Maximum depth
- LeetCode_237. Delete Node in a Linked List
- leetCode_Move Zeroes_
- LeetCode_ Invert Binary Tree
- LeetCode_SameTree
- Leetcode——valid Anagram——时间复杂度太高,怎么办??
- leetcode_Excel Sheet Column Number
- Leetcode——Contains Duplicate
- ORACLE-019:ORACLE常用SQL优化hint语句
- Android开发中BUG、错误汇总(不断更新)
- 基于SEDA的异步框架设计与实现
- wchar_t
- linux(ubuntu)下C++访问mysql数据库