您的位置:首页 > 其它

[Leetcode 7] 101 Symmetric Tree

2013-04-07 08:49 561 查看
Problem:

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


Analysis:

Recursion can help in this problem. Write a helper function which accepts two TreeNode arguments, if all of them are null, return true; only one of them is null, return false; both of them are not null, if t1.val != t2.val, return false, else compare t1.left with t2.right and t1.right with t2.left. Most of this check is the same as Same Tree problem, the only difference is when current two nodes are the same, instead of checking two node's children corresponding, we check left with right and right with left. The recursion is so fantastic!!!

Another way to solve this problem is to use iterative method.

The basic thought is use two queues, one is used to store the left sub tree of root node, we call it queueLeft; and the other is used to stroe the right sub tree of root node, we call it queueRight;

queueLeft always enqueues the current node's left child and then right child; queueRight performs on the contrary way, always enqueues the current node's right child first and then its left child. To deal with node only has one child case, we introduce the nullNode to represent such a null to keep the basic structure of the binary tree. Then we continue dequeue, compare, and then enqueue.

There is a tricky problem in this solution. Given a tree as follows:

1
/    \
2      2
/ \    / \
3   4   4  3
/ \    / \
8   9   9  8

If we just enqueue those null Node into each queue, the result of this tree is true, which actually is false. So we must make sure that, enqueue performs on the same structure of child nodes.

Code:

A Wrong Implementation of Enqueue

if (tl.left!=null || tl.right!=null) {
enqueue(tl.left, ql, nullNode);
enqueue(tl.right, ql, nullNode);
}

if (tr.left!=null || tr.right!=null) {
enqueue(tr.right, qr, nullNode);
enqueue(tr.left, qr, nullNode);
}


Attention:

To check whether two trees are symmetric, use the helper function checkSymmetric() alone.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: