leetcode-101对称二叉树

leetcode-101对称二叉树
题解

  1. 递归
/**
 * 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:
    vector<int>res;
    bool dfs(TreeNode *p,TreeNode *q){
        if(p != NULL && q != NULL){
            if(p->val == q->val && dfs(p->left,q->right) && dfs(p->right,q->left))return true;
        }
        else if(p == NULL && q == NULL)return true;
        return false;
    }
    bool isSymmetric(TreeNode* root) {
        return dfs(root,root);
    }
};
  1. 迭代
/**
 * 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:
    queue<TreeNode *>q;
    bool isSymmetric(TreeNode* root) {
        q.push(root),q.push(root);
        TreeNode *left,*right;
        while(!q.empty()){
            left = q.front();
            q.pop();
            right = q.front();
            q.pop();
            if(left != NULL && right == NULL || left == NULL && right != NULL)return false;
            if(left != NULL && right != NULL && left->val != right->val)return false;
            if(left == NULL)continue;
            q.push(left->left),q.push(right->right);
            q.push(left->right),q.push(right->left);
        }
        return true;
    }
};
上一篇:Qt+FFMPEG学习(二)屏幕录制+实时显示(GDIGRAB)


下一篇:LeetCode:101. 对称二叉树