Same Tree

来源:互联网 发布:易语言注入dll源码 编辑:程序博客网 时间:2024/06/01 10:38

题目:

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返回true,一个null一个不为null返回false,代码如下:

/** * Definition for a binary tree node. * 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;        } else {            if(p == null || q == null) {                return false;            } else {                return p.val == q.val && isSameTree(p.left,q.left) && isSameTree(p.right,q.right);            }        }    }}


0 0
原创粉丝点击