Leetcode-same-tree

来源:互联网 发布:安卓手机怎么查mac 编辑:程序博客网 时间:2024/06/03 15:50

题目描述


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 class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    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 false;        return isSameTree(p.left,q.left)&&isSameTree(p.right,q.right);      }}


代码比较清晰,不再赘述。

0 0
原创粉丝点击