LeetCode——Symmetric Tree
# 101
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.
这题是要求判断二叉树是否对称。要求用递归和迭代。这题的思路其实并不难,因为是二叉树。先写出以下几种情况:
1. root为空,返回true,开始递归
2. root非空,无子节点,返回true
3. 如果不是左右子节点都存在且相等,返回false
4. 左右子节点存在且相当,再分别比较左右子树,形成递归
需要第一一个递归函数。这题的递归不难,只要把思路理清,很容易就写出来了。
- C++/递归方法
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(!root)
return true;
return isSymmetric(root -> left,root -> right);
}
bool isSymmetric(TreeNode* left,TreeNode* right){
if(!left && !right)
return true;
if((left && !right) || (!left && right) || (left -> val != right -> val))
return false;
return isSymmetric(left -> left,right -> right) && isSymmetric(left -> right,right -> left);
}
};
迭代的方法其实核心思想是一样的,只需要转换一下就可以了。
- C++/迭代方法
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(!root)
return true;
queue<TreeNode*>q1,q2;
q1.push(root -> left);
q2.push(root -> right);
while (!q1.empty() && !q2.empty()){
TreeNode* left = q1.front();
q1.pop();
TreeNode* right = q2.front();
q2.pop();
if (left == NULL && right == NULL)
continue;
if (left == NULL || right == NULL)
return false;
if (left -> val != right -> val)
return false;
q1.push(left ->l eft);
q1.push(left -> right);
q2.push(right -> right);
q2.push(right -> left);
}
return true;
}
};
使用的是DFS深度优先搜索的算法,其实也可以用BFS广度优先搜索,差别不是很大,不同的比较方式,下面用Python实现。
- Python
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
queuel, queuer = [root.left], [root.right]
while len(queuel) > 0 and len(queuer) > 0:
left = queuel.pop()
right = queuer.pop()
if not left and not right:
continue
elif not left or not right:
return False
if left.val != right.val:
return False
queuel.insert(0, left.left)
queuel.insert(0, left.right)
queuer.insert(0, right.right)
queuer.insert(0, right.left)
return len(queuel) == 0 and len(queuer) == 0