A100 正确使用递归和灵活使用if

来源:互联网 发布:二手软件app软件哪个好 编辑:程序博客网 时间:2024/06/05 07:45

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 static boolean isSameTree(TreeNode p, TreeNode q) {        if(p == null && q == null){        return true;    }else if(p == null || q == null){//说明不可能都是null了        return false;    }else if(p.val != q.val){//经过上两个说明都不为空了        return false;    }        boolean isSameTreeLeft = isSameTree(p.left, q.left);    boolean isSameTreeRight = isSameTree(p.right, q.right);     return isSameTreeLeft && isSameTreeRight;}

递归一定要找到合适的出口,只有p,q都不为空的时候再接着递归

0 0
原创粉丝点击