101. Symmetric Tree
Given the root
of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
Example 1:
Input: root = [1,2,2,3,4,4,3] Output: true
Example 2:
Input: root = [1,2,2,null,3,null,3] Output: false
Constraints:
- The number of nodes in the tree is in the range
[1, 1000]
. -100 <= Node.val <= 100
Follow up: Could you solve it both recursively and iteratively?
遍历法:
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=inside && outside;
return issame;
}
bool isSymmetric(TreeNode* root) {
if(root==NULL)return true;
return compare(root->left,root->right);
}
};
首先,如果根节点为空,true
否则,进入compare函数中进行递归,
compare函数:1,左右节点一空一不空,false
2,左右都空,true
3,左右数值不同,false
4,比较左右子树:outside(left的left,right的right)和inside(left的right,right的left),最后返回outside和inside是否相同
迭代法:
队列:
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==NULL && rightNode==NULL)continue;
else if(leftNode==NULL && rightNode!=NULL)return false;
else if(leftNode!=NULL && rightNode==NULL)return false;
else if(leftNode->val!=rightNode->val)return false;
que.push(leftNode->left);
que.push(rightNode->right);
que.push(leftNode->right);
que.push(rightNode->left);
}
return true;
}
};
其实这个和递归法的核心思想是一样的,但是有一个点需要注意,判断出左右节点都为空的时候不能直接返回true,而是continue。但是递归法中可以直接返回false,是因为递归法每次都会判断一层的节点
栈:
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(root==NULL)return true;
stack<TreeNode*>stk;
stk.push(root->left);
stk.push(root->right);
while(!stk.empty()){
TreeNode*rightNode=stk.top();stk.pop();
TreeNode*leftNode=stk.top();stk.pop();
if(leftNode==NULL && rightNode==NULL)continue;
else if(leftNode==NULL && rightNode!=NULL)return false;
else if(leftNode!=NULL && rightNode==NULL)return false;
else if(leftNode->val!=rightNode->val)return false;
stk.push(leftNode->left);
stk.push(rightNode->right);
stk.push(leftNode->right);
stk.push(rightNode->left);
}
return true;
}
};
这个与队列几乎一样的,没什么好说的
100. Same Tree
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if(p==NULL && q==NULL)return true;
else if(p==NULL || q==NULL )return false;
else if(p->val!=q->val)return false;
return isSameTree(p->left,q->left) && isSameTree(p->right,q->right);
}
};