leetcode----------Same Tree

题目

Same Tree

通过率 42.0%
难度 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.

 

   初步构想:二叉树判断相等问题,肯定是先判断左子树再判断右子树哇,但是,树空!!!!

   注意事项:

        1. 树空的情况!

        2. 注意先判断节点值,再继续递归!

  解题思路:

     1. 先判断空的情况,这里分为三种:p和q均为空,p为空q不为空,p不为空q为空。

     2. 对于不空的情况,先判断p和q的根节点的值,相等递归左右子树继续判断,否则返回false。

     3. 继续递归的情况,要注意p和q相等的条件是左右子树均都相等。

 

java代码如下:

 1 /**
 2  * Definition for binary tree
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public boolean isSameTree(TreeNode p, TreeNode q) {
12         if(p==null && q==null) return true;
13         if(p!=null && q==null) return false;
14         if(p==null && q!=null) return false;
15         if(p.val==q.val)
16         {
17             return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
18         }else
19         {
20             return false;
21         }
22     }
23 }
24   

 

                                                          2014-12-13

                                                             17:13:10

                                                             软微3202

转载于:https://www.cnblogs.com/pku-min/p/4161618.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值