Leet Code OJ 100. Same Tree [Difficulty: Easy]

题目:
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.

翻译:
给2个二叉树,写一个程序去检验它们是否“相同”。
如果2个二叉树的结构相同,并且它们的节点有相同的值,则被认为是“相同”的。

分析:
我的做法是递归判断这两棵树的左右子树,然后判断它们的值是否相等。

代码:

/** * 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;
        }
        if(p==null||q==null){
            return false;
        }
        boolean left=isSameTree(p.left,q.left);
        boolean right=isSameTree(p.right,q.right);
        boolean val=(p.val==q.val);
        if(left&&right&&val){
            return true;
        }else{
            return false;
        }
    }
}

你可能感兴趣的:(LeetCode,算法,二叉树)