递归: 递归三部曲: 1、确定递归函数的参数和返回值 要比较的是根节点的两个子树是否是相互翻转的,进而判断这个树是不是对称树,所以参数是左子树结点和右子树结点。返回值为bool类型 2、确定终止条件 结点为空的情况和不为空的情况
if(left == NULL && right!=NULL){
return false;
}
else if(left!=NULL && right==NULL){
return false;
}
else if(left == NULL && right == NULL){
return true;
}else if(left->val != right->val){
return false;
}
3、确定单层递归逻辑 单层递归的逻辑就是处理左右结点均不为空,且数值相同的情况。 比较左节点的左孩子和右节点的右孩子,比较左节点的右孩子和右节点的左孩子,如果左右都对称就返回true。否则返回false
class Solution {
public:
bool compare(TreeNode*left,TreeNode*right){
if(left == NULL && right!=NULL){
return false;
}
else if(left!=NULL && right==NULL){
return false;
}
else if(left == NULL && right == NULL){
return true;
}else if(left->val != right->val){
return false;
}
bool outside = compare(left->left,right->right);
bool inside = compare(left->right,right->left);
bool isSame = outside && inside;
return isSame;
}
bool isSymmetric(TreeNode* root) {
if(root ==NULL){
return true;
}
return compare(root->left,root->right);
}
};
迭代:队列实现
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(root == NULL){
return true;
}
queue<TreeNode*> que;
que.push(root->left);
que.push(root->right);
while(!que.empty()){
TreeNode * leftNode = que.front();
que.pop();
TreeNode* rightNode = que.front();
que.pop();
if(!leftNode && !rightNode){
continue;
}
if((!leftNode || !rightNode || (leftNode->val!=rightNode->val))){
return false;
}
que.push(leftNode->left);
que.push(rightNode->right);
que.push(leftNode->right);
que.push(rightNode->left);
}
return true;
}
};
栈实现:把队列换成栈即可 两个结点两个结点取出来比较
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(root == NULL){
return true;
}
stack<TreeNode*> st;
st.push(root->left);
st.push(root->right);
while(!st.empty()){
TreeNode * leftNode = st.top();
st.pop();
TreeNode* rightNode = st.top();
st.pop();
if(!leftNode && !rightNode){
continue;
}
if((!leftNode || !rightNode || (leftNode->val!=rightNode->val))){
return false;
}
st.push(leftNode->left);
st.push(rightNode->right);
st.push(rightNode->left);
st.push(leftNode->right);
}
return true;
}
};
|