【LeetCode】Symmetric Tree

【Description】

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

    1
   / \
  2   2
 / \ / \
3  4 4  3

 

But the following [1,2,2,null,3,null,3] is not:

    1
   / \
  2   2
   \   \
   3    3

 

Note:
Bonus points if you could solve it both recursively and iteratively.

 

【AC code】

Reference: https://leetcode.com/articles/symmetric-tree/

一、递归  时间复杂度:O(n)

 1 class Solution {
 2     public boolean isSymmetric(TreeNode root) {
 3         if (root == null) return true;
 4         return isSymmetric(root.left, root.right);
 5     }
 6     private boolean isSymmetric(TreeNode r1, TreeNode r2) {
 7         if (r1 == null && r2 == null) return true;
 8         if ((r1 == null || r2 == null) || r1.val != r2.val) return false;
 9         return isSymmetric(r1.left, r2.right) && isSymmetric(r1.right, r2.left);
10     }
11 }
View Code

二、迭代  时间复杂度:O(n)

 1 class Solution {
 2     public boolean isSymmetric(TreeNode root) {
 3         Queue q = new LinkedList<>();
 4         q.add(root);
 5         q.add(root);
 6         while (!q.isEmpty()) {
 7             TreeNode t1 = q.poll();
 8             TreeNode t2 = q.poll();
 9             if (t1 == null && t2 == null) continue;
10             if (t1 == null || t2 == null) return false;
11             if (t1.val != t2.val) return false;
12             q.add(t1.left);
13             q.add(t2.right);
14             q.add(t1.right);
15             q.add(t2.left);
16         }
17         return true;
18     }
19 }
View Code

 

你可能感兴趣的:(【LeetCode】Symmetric Tree)