Same Tree 判断两棵树是不是相同

来源:互联网 发布:vr设计软件 编辑:程序博客网 时间:2024/05/22 09:39

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.

判断两棵树是否一样是看:

1. 它们的当前节点值是否一样

2. 它们的左子树是否一样

3. 它们的右子树是否一样

递归解决

运行时间:


代码:

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


1 0