http://oj.leetcode.com/submissions/detail/2861451/
[quote]
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
[/quote]
1. 用递归相对简单
2. 非递归,注意要点有
[list]
[*] 向stack 里放子结点时要从右到左,先放结点的右结点,再放左结点,那样pop出来时,才会从左到右,提交了好多次才成功!
[*] 判断左子结点与右子结点数目一致,还不够,因为如上图,3443,第一个4有子树,然后第二个3有子树,数目一样,但位置不同!
[/list]
[quote]
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
[/quote]
1. 用递归相对简单
2. 非递归,注意要点有
[list]
[*] 向stack 里放子结点时要从右到左,先放结点的右结点,再放左结点,那样pop出来时,才会从左到右,提交了好多次才成功!
[*] 判断左子结点与右子结点数目一致,还不够,因为如上图,3443,第一个4有子树,然后第二个3有子树,数目一样,但位置不同!
[/list]
public boolean isSymmetric(TreeNode root) {
if (root == null) {
return true;
}
return isSame(root);
}
public boolean isSame(TreeNode root) {
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
while (stack.size() > 0) {
TreeNode[] nodes = new TreeNode[stack.size()];
for (int i = 0; i < nodes.length; i++) {
nodes[i] = stack.pop();
}
if (nodes.length % 2 != 0) {
if (nodes.length == 1) {
if (nodes[0] != root) {
return false;
}
} else {
return false;
}
}
int mid = nodes.length / 2;
for (int i = 0; i < mid; i++) {
TreeNode l = nodes[i];
TreeNode r = nodes[nodes.length - i - 1];
if (l == null || r == null) {
if (l != r) {
return false;
}
} else if (l.val != r.val) {
return false;
}
}
int leftNb = 0;
int rightNb = 0;
for (int i = nodes.length - 1; i >= 0; i--) {
if (nodes[i] == null) {
continue;
}
if (nodes[i].right != null) {
stack.push(nodes[i].right);
rightNb++;
} else {
stack.push(null);
}
if (nodes[i].left != null) {
stack.push(nodes[i].left);
leftNb++;
} else {
stack.push(null);
}
}
if (leftNb != rightNb) {
return false;
}
if (leftNb == 0) {
stack.clear();
}
}
return true;
}