LeetCode 100 Same Tree

来源:互联网 发布:java list集合排序 编辑:程序博客网 时间:2024/05/18 02:04

题目描述

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.

分析

用递归,首先要判断输入的两个结点,是否同时为null,还是其中一个为null,否则会出现异常。

p.val和q.val相等,同时结点左右结点同时满足这个规则,则相等。

代码

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