题目描述:
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.
常规的二叉树问题,递归的解法:
/**
* 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 == 0)
return true;
return isMirror(root -> left, root -> right);
}
private:
bool isMirror(TreeNode* t1, TreeNode* t2){
if(t1 == 0 && t2 == 0)
return true;
if(t1 == 0 || t2 == 0)
return false;
if(t1 -> val != t2 -> val)
return false;
return isMirror(t1 -> left, t2 -> right) && isMirror(t1 -> right, t2 -> left);
}
};
由于每个顶点都需要遍历一遍,所以这个算法的时间复杂度为O(n),了leetcode上运行时间为4ms,由于用到了递归,所以空间复杂度为树的高度,在最差的情况下,树高为n,因此最差情况下空间复杂度为O(n)。
非递归解法:
/**
* 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 == 0)
return true;
stack<treePair> s;
s.push(treePair(root -> left, root -> right));
while(!s.empty()){
treePair tmp;
tmp = s.top();
s.pop();
TreeNode *t1, *t2;
t1 = tmp.t1, t2 = tmp.t2;
if(t1 == 0 && t2 == 0)
continue;
if(t1 == 0 || t2 == 0)
return false;
if(t1 -> val != t2 -> val)
return false;
s.push(treePair(t1 -> left, t2 -> right));
s.push(treePair(t1 -> right, t2 -> left));
}
return true;
}
private:
struct treePair{
TreeNode *t1, *t2;
treePair(TreeNode* x = 0, TreeNode* y = 0):t1(x), t2(y){}
};
};
时空复杂度与上面的递归方法是一致的,运行时间也是4ms。
在leetcode上有篇 题解,里面也提供了两种方法,但是,里面采用了isMirror(root, root),这个函数,结果虽然没有错,代码也简洁了,但是实际上这是将原来的树作为一棵新树的左右节点,所以后面的比较也会翻倍,但在时间复杂度而言来说是一样的(N和2N是一致的),而这会导致很多没必要的计算,还不如多写个判断,程序也容易理解。
以上纯属个人理解。