LeetCode 100 same tree

public boolean isSameTree(TreeNode p, TreeNode q) { }java

this is the kind of problem that can use recursion, and all we have to do is write the write equations:ide

isSameTree(p, q) = (p.val == q.val) && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
注意返回到達底層的返回條件便可。this

class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        //isSameTree(p, q) = (p.value == q.value) && isSameTree(p.left, q.left) && isSameTree(p.right, q.right)
        if (p == null && q == null) {
            return true;
        }
        if (p == null || q == null) {
            return false;
        }
        return (p.val == q.val) && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }
}
相關文章
相關標籤/搜索