给你一个二叉树的根节点 root , 检查它是否轴对称。
示例 1:
输入:root = [1,2,2,3,4,4,3]
输出:true
示例 2:
输入:root = [1,2,2,null,3,null,3]
输出:false
提示:
树中节点数目在范围 [1, 1000] 内
-100 <= Node.val <= 100
进阶:你可以运用递归和迭代两种方法解决这个问题吗?
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/symmetric-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
递归:
/** * 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 { bool Treeis(TreeNode* left, TreeNode* right) { if (!left && !right) return true; if (!left || !right) return false; return( (left -> val == right -> val) && Treeis(left -> left, right ->right) && Treeis (left -> right, right -> left) ); } public: bool isSymmetric(TreeNode* root) { return Treeis (root -> left, root -> right); } };
迭代:
/** * 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 check(TreeNode *left, TreeNode *right) { queue <TreeNode*> q; // 引入队列 q.push(left); q.push(right); // 将两个节点入队 while (!q.empty()) { // 如果队列非空 left = q.front(); q.pop(); // 每一次出队比较两个节点 right = q.front(); q.pop(); if (!left && !right) continue; // 如果两个节点都为空,跳出循环 if ((!left || !right) || (left->val != right->val)) return false; // 如果只有一方为空或者左右不相等就返回false q.push(left->left); // 按照对称的顺序入队 q.push(right->right); q.push(left->right); q.push(right->left); } return true; } bool isSymmetric(TreeNode* root) { return check(root, root); } };
标签:right,TreeNode,val,nullptr,-----,二叉树,101,root,left From: https://www.cnblogs.com/slowlydance2me/p/16886785.html