关闭

Leetcode 100. Same Tree

45人阅读 评论(0) 收藏 举报

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);
}



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:598次
    • 积分:104
    • 等级:
    • 排名:千里之外
    • 原创:10篇
    • 转载:2篇
    • 译文:0篇
    • 评论:0条
    文章存档