码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-08-12 23:43:01      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:

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

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

标签:

原文地址:http://my.oschina.net/Tsybius2014/blog/491629

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!