2014年10月4日星期六

[Leetcode] 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.
比较简单的树的遍历题目,判断当前两个节点的val是否相同以及左右子树是否same即可。

public boolean isSameTree(TreeNode p, TreeNode q) {
        if(p == null && q == null) return true;
        else if(p == null || q == null) return false;
        else {
            return p.val == q.val & isSameTree(p.left, q.left) & isSameTree(p.right, q.right);
        }
    }

没有评论:

发表评论