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: