Leetcode OJ平台上的SameTree题目用Java递归实现

上一篇 / 下一篇  2014-06-03 10:00:44 / 个人分类:学习

原题目如下:

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.


java递归实现,关键是想清楚递归终止条件,谢谢木易先森


/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public static  boolean isSameTree(TreeNode p, TreeNode q){
        if(p == null && q == null)
            return true;
        else if(p == null || q ==null) // one of them is null
            return false;
        else if(p.val != q.val)
            return false;
        else
            return (isSameTree(p.left,q.left) && isSameTree(p.right,q.right));
    }
}


TAG:

 

评分:0

我来说两句

我的栏目

日历

« 2024-04-20  
 123456
78910111213
14151617181920
21222324252627
282930    

数据统计

  • 访问量: 17687
  • 日志数: 12
  • 建立时间: 2014-05-21
  • 更新时间: 2014-06-03

RSS订阅

Open Toolbar