-
Notifications
You must be signed in to change notification settings - Fork 0
101. Symmetric Tree
Jacky Zhang edited this page Aug 15, 2016
·
1 revision
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.
Tree类题目。
##Approach 1: recursive symmetric tree的特点是root的左右两棵子树呈镜像。
两棵树呈镜像的条件是:
- 两棵树的root有相同的value;
- 一颗树的左子树与另一棵树的右子树呈镜像。
因此可采用recursive的方法,一层一层地向下判断,再返回结果。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isSymmetric(TreeNode root) {
if(root == null) return true;
return isMirror(root.left, root.right);
}
private boolean isMirror(TreeNode n1, TreeNode n2) {
if(n1 == null && n2 == null) return true;
if(n1 == null || n2 == null) return false;
return (n1.val == n2.val) && (isMirror(n1.left, n2.right)) && (isMirror(n1.right, n2.left));
}
}##Approach 2: iterative
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isSymmetric(TreeNode root) {
if(root == null) return true;
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root.left);
queue.add(root.right);
while(!queue.isEmpty()) {
TreeNode n1 = queue.poll();
TreeNode n2 = queue.poll();
if(n1 == null && n2 == null) continue;
if(n1 == null || n2 == null) return false;
if(n1.val != n2.val) return false;
queue.add(n1.left);
queue.add(n2.right);
queue.add(n1.right);
queue.add(n2.left);
}
return true;
}
}