[LeetCode]100. Same Tree

来源:互联网 发布:ftp服务使用的端口是 编辑:程序博客网 时间:2024/06/08 13:52

题目描述: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.
分析:判断两个二叉树是否相等

解题思路:递归判断两颗子树是否相等。判断条件:都为叶子结点返回true;其中一个节点存在,另一个节点不存在返回false;两个节点都存在,且相等,递归该节点的左子树和右子树,不想等则返回false。

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