LeetCode:Same Tree - 判断两颗树是否相等

一、题目名称java

Same Tree(判断两棵树是否相等)node

二、题目地址ide

https://leetcode.com/problems/same-tree/函数

三、题目内容code

英文: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.递归

中文:给定两颗二叉树,写一个函数判断这两棵树是否相等。若是两棵树的结构和各节点中保存的值是相等的,则认为这两棵树相等。leetcode

四、解题方法开发

本题能够采用先根遍历的方法,从上到下递归考察各节点。在任意一对节点的比较中,若是左右枝是否为空的属性和节点中的val值不相等,则认为两棵树不是同一棵树,不然继续考察。若是遍历结束后仍然不能证实这两棵树不是同一棵树,则这两棵树就是相等的get

解决问题的Java代码以下:it

/**
 * 功能说明:LeetCode 100 - Same Tree
 * 开发人员:Tsybius2014
 * 开发时间:2015年8月12日
 */
public class Solution {
    
    /**
     * 判断两个树是否为相等
     * @param p 树p
     * @param q 树q
     * @return
     */
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null && q == null) {
            return true;
        } else if (
            (p == null && q != null) || 
            (p != null && q == null) || 
            p.val != q.val || 
            !isSameTree(p.left, q.left) || 
            !isSameTree(p.right, q.right)) {
            return false;
        } else {
            return true;
        }
    }
}

END

相关文章
相关标签/搜索