LeetCode_SameTree

来源:互联网 发布:域名添加a记录 编辑:程序博客网 时间:2024/06/05 22:45

100. Same Tree


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
原创粉丝点击