LeetCode:Same Tree

[亡魂溺海] 提交于 2019-12-15 20:29:28

【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>

1、题目名称

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

2、题目地址

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

3、题目内容

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

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

4、解题方法

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

解决问题的Java代码如下:

/**
 * 功能说明: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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!