leetcode 101. Symmetric Tree
- Symmetric Tree:题目链接
DFS-递归
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| class Solution { public boolean isMirror(TreeNode t1, TreeNode t2) { if (t1 == null && t2 == null) { return true; } if (t1 == null || t2 == null || t1.val != t2.val) { return false; } return isMirror(t1.left, t2.right) && isMirror(t1.right, t2.left); } public boolean isSymmetric(TreeNode root) { if (root == null) { return true; } return isMirror(root.left, root.right); } }
|
BFS
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
| class Solution { public boolean BFS(TreeNode t1, TreeNode t2) { Queue<TreeNode> q1 = new LinkedList<>(); Queue<TreeNode> q2 = new LinkedList<>(); q1.offer(t1); q2.offer(t2); while (!q1.isEmpty() && !q2.isEmpty()) { TreeNode f1 = q1.poll(); TreeNode f2 = q2.poll(); if (f1 == null && f2 == null) { continue; } if (f1 == null || f2 == null || f1.val != f2.val) { return false; } q1.offer(f1.left); q1.offer(f1.right); q2.offer(f2.right); q2.offer(f2.left); } if (!q1.isEmpty() || !q2.isEmpty()) { return false; } return true; } public boolean isSymmetric(TreeNode root) { if (root == null) { return true; } return BFS(root.left, root.right); } }
|