Skip to content

Commit f0aed18

Browse files
author
applewjg
committed
Same Tree
Change-Id: I2ab046652c7fcf933ba91566d40ba686a5deab05
1 parent 99971b3 commit f0aed18

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

SameTree.java

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/*
2+
Author: King, [email protected]
3+
Date: Dec 25, 2014
4+
Problem: Same Tree
5+
Difficulty: easy
6+
Source: http://leetcode.com/onlinejudge#question_100
7+
Notes:
8+
Given two binary trees, write a function to check if they are equal or not.
9+
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
10+
11+
Solution: recursion.
12+
*/
13+
/**
14+
* Definition for binary tree
15+
* public class TreeNode {
16+
* int val;
17+
* TreeNode left;
18+
* TreeNode right;
19+
* TreeNode(int x) { val = x; }
20+
* }
21+
*/
22+
public class Solution {
23+
public boolean isSameTree(TreeNode p, TreeNode q) {
24+
if (p == null && q == null) return true;
25+
if ((p != null && q == null) || (p == null && q != null)) return false;
26+
if (p.val != q.val) return false;
27+
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
28+
}
29+
}

0 commit comments

Comments
 (0)