101. Symmetric Tree(树的对称)
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.
方法一:递归
时间复杂度:o(n) 空间复杂度:o(1)
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public boolean isSymmetric(TreeNode root) { if(root==null) return true; return isSymmetric(root.left,root.right); } private boolean isSymmetric(TreeNode left,TreeNode right){ if(left==null && right==null) return true; if(left==null || right==null) return false; if(right.val != left.val) return false; return isSymmetric(left.left,right.right)&&isSymmetric(left.right,right.left); } }
方法二:迭代
时间复杂度:o(n) 空间复杂度:o(1)
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public boolean isSymmetric(TreeNode root) { Queue<TreeNode> q1=new LinkedList<TreeNode>(); Queue<TreeNode> q2=new LinkedList<TreeNode>(); q1.add(root); q2.add(root); while (!q1.isEmpty()&&!q2.isEmpty()){ TreeNode t1=q1.poll(); TreeNode t2=q2.poll(); if(t1==null&&t2==null) continue; if(t1==null||t2==null) return false; if(t1.val!=t2.val) return false; q1.add(t1.left); q1.add(t1.right); q2.add(t2.right); q2.add(t2.left); } return true; } }
苟有恒,何必三更眠五更起;最无益,莫过一日暴十日寒。