Symmetric Tree
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1 / \ 2 2 / \ / \ 3 4 4 3
But the following is not:
1 / \ 2 2 \ \ 3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
confused what "{1,#,2,3}" means?
思想:递推
java代码:
- public boolean isSymmetric(TreeNode left,TreeNode right) {
- if(left==null && right==null) return true;
- if(left == null || right == null) return false;
- if(left.val != right.val) return false;
- boolean flag = isSymmetric(left.left,right.right) && isSymmetric(left.right,right.left);
- return flag;
- }
- public boolean isSymmetric(TreeNode root) {
- if(root==null) return true;
- if(root.left==null && root.right==null) return true;
- return isSymmetric(root.left,root.right);
- }
思想二:迭代
注意事项:java 中Queue是一个接口,需要用LinkedList来初始化。提供来offer和poll来添加和移除数据,如果溢出,返回false或者不存在,则返回null。相对于add和remove安全一些,或者说add和remove会首先根据offer和poll的结果来判断是否存在异常。
Queue中的peek返回头节点,如果不存在则返回null。
- public boolean isSymmetric(TreeNode root) {
- if(root==null) return true;
- if(root.left==null && root.right==null) return true;
- Queue<TreeNode> q = new LinkedList<TreeNode>();
- Queue<TreeNode> p = new LinkedList<TreeNode>();
- if(root.left!=null) q.offer(root.left);
- if(root.right!=null) p.offer(root.right);
- while(q.peek() != null || p.peek() != null) {
- TreeNode left = q.poll();
- TreeNode right = p.poll();
- if(left==null || right==null) return false;
- if(left.val == right.val) {
- if(left.left!=null && right.right!=null) {
- q.offer(left.left);
- p.offer(right.right);
- } else if(left.left!=null || right.right!=null) {
- return false;
- }
- if(left.right!=null && right.left!=null) {
- q.offer(left.right);
- p.offer(right.left);
- } else if(left.right!=null || right.left!=null) {
- return false;
- }
- } else {
- return false;
- }
- }
- return true;
- }

浙公网安备 33010602011771号