对称二叉树
作者:互联网
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
// class Solution {
// public:
// bool helper(TreeNode* p, TreeNode* q){
// //终止条件
// if(!p && !q) return true;
// if(!p || !q) return false;
// if(p->val != q->val) return false;
// //递归逻辑
// return helper(p->left, q->right) && helper(p->right, q->left);
// }
// bool isSymmetric(TreeNode* root) {
// //若空
// if(root == nullptr) return true;
// return helper(root, root);
// }
// };
//迭代,队列
// class Solution{
// public:
// bool isSymmetric(TreeNode* root){
// //若空
// if(root == nullptr) return true;
// queue<TreeNode*> que;
// que.push(root);
// que.push(root);
// 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 == nullptr) return true;
//
stack<TreeNode*> stk;
stk.push(root);
stk.push(root);
while(!stk.empty()){
//左右节点比较
TreeNode* leftnode = stk.top(); stk.pop();
TreeNode* rightnode = stk.top();stk.pop();
//若空
if(!leftnode && !rightnode) continue;
//非空
if(!leftnode || !rightnode || (leftnode->val != rightnode->val)) return false;
//压入新值
stk.push(leftnode->left);
stk.push(rightnode->right);
stk.push(leftnode->right);
stk.push(rightnode->left);
}
return true;
}
};
标签:right,return,TreeNode,stk,que,二叉树,对称,leftnode 来源: https://blog.csdn.net/kangjielearning/article/details/114990467