Leetcode 100. Same Tree

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.

我的代码:

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 if(q == null && p != null){
            return false;
        }
        else if( p.val == q.val){
            if(isSameTree(p.left, q.left) == true && isSameTree(p.right, q.right) == true){
                return true;
            }
            else{
                return false;
            }
        }
        else{
            return false;
        }
    }
}
discuss中的更优解

public boolean isSameTree(TreeNode p, TreeNode q) {
    if(p == null && q == null) return true;
    if(p == null || q == null) return false;<span style="white-space:pre">	</span>//此处合并了我第2、3个else if
    return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}



阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

Leetcode 100. Same Tree

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭