Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
46 lines (40 loc) · 1.24 KB

File metadata and controls

46 lines (40 loc) · 1.24 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/**
* #101 Symmetric Tree
* see link : https://leetcode-cn.com/problems/symmetric-tree/
* 和 #100. Same Tree 类似 使用递归解法 O(n)
*/
public class S101 {
public static boolean isSymmetric(TreeNode root) {
if(root == null) {
return true;
}
return symmetric(root.left, root.right);
}
public static boolean symmetric(TreeNode p, TreeNode q) {
if(p == null || q == null)
return p == q ? true : false;
//
return p.val == q.val && symmetric(p.right, q.left) && symmetric(p.left, q.right);
}
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public static void main(String[] args) {
//check demo
TreeNode n1 = new TreeNode(1);
TreeNode n2_left = new TreeNode(2);
TreeNode n2_right = new TreeNode(2);
n1.left = n2_left;
n1.right = n2_right;
TreeNode n3_left = new TreeNode(3);
TreeNode n3_right = new TreeNode(4);
n2_left.left = n3_left;
n2_left.right = n3_right;
n2_right.left = n3_right;
n2_right.right = n3_left;
System.out.println("isSymmetric(n1) > " + isSymmetric(n1));
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.