leetcode 101. Symmetric Tree 判断对称树,递归和迭代
2016-04-30 21:23
453 查看
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
But the following is not:
使用递归,判断代码如下:
使用迭代,广度优先使用队列,这里使用两个队列,分别代表根节点的左右孩子作为根的树,判断这两个队列是否对称。
For example, this binary tree is symmetric:
1 / \ 2 2 / \ / \ 3 4 4 3
But the following is not:
1 / \ 2 2 \ \ 3 3
使用递归,判断代码如下:
public boolean isSymmetric(TreeNode root) { if(root==null) return true; return isSymmetric(root.left,root.right); } public boolean isSymmetric(TreeNode l,TreeNode r){ if(l==null && r==null) return true; if(l==null || r==null) return false; if(l.val==r.val) return isSymmetric(l.left,r.right) && isSymmetric(l.right,r.left); return false; }
使用迭代,广度优先使用队列,这里使用两个队列,分别代表根节点的左右孩子作为根的树,判断这两个队列是否对称。
public boolean isSymmetric(TreeNode root) { if(root==null) return true; Queue<TreeNode> ql=new LinkedList<>(); Queue<TreeNode> qr=new LinkedList<>(); ql.offer(root.left); qr.offer(root.right); while(!ql.isEmpty() ){ TreeNode left=ql.poll(); TreeNode right=qr.poll(); if(left==null && right==null){ continue; } if(left==null || right==null || left.val!=right.val){ return false; } ql.offer(left.left); ql.offer(left.right); qr.offer(right.right); qr.offer(right.left); } return true; }
相关文章推荐
- NYOJ 791 Color the fence
- iOS笔记----Hybrid应用基本核心
- 个人工作总结07
- SDUT 2416:Fruit Ninja II
- HDU-4496 D-City (并查集)
- Android NFC
- Qt多线程程序设计
- 树的最大独立集(1初步)
- 课程设计__类和对象的简单使用(构造函数初始化)
- ConcurrentHashMap实现原理
- Log4cpp介绍及使用
- 《Nodejs开发加密货币》之二:Nodejs原来在币圈如此流行?
- 内存操作函数memmove,memcpy,memset
- 构建之法05
- c++ Multisets
- 1053. 住房空置率 (20)
- libevent 构造httpServer
- Qt如何实现多窗口调用
- CountDownLatch,一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待
- win32 错误码转换到文字