首页 > 代码库 > [leetCode] Symmetric Tree
[leetCode] Symmetric Tree
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1 / 2 2 / \ / 3 4 4 3
But the following is not:
1 / 2 2 \ 3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
思路一:递归思想。时间复杂度O(n),空间复杂度O(logN)
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */10 class Solution {11 public:12 bool isSymmetric(TreeNode *root) {13 if (root == NULL) return true;14 return isSymmetric(root->left, root->right);15 }16 bool isSymmetric(TreeNode *root1, TreeNode *root2) {17 if (!root1 && !root2) return true;18 if (!root1 || !root2) return false;19 if (root1->val != root2->val) return false;20 21 return isSymmetric(root1->left, root2->right) && isSymmetric(root1->right, root2->left);22 }23 };
思路二:迭代。层次遍历的思想。时间复杂度O(n),空间复杂度O(logN)
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */10 class Solution {11 public:12 bool isSymmetric(TreeNode *root) {13 if (root == NULL) return true;14 queue<TreeNode *> q;15 q.push(root->left);16 q.push(root->right);17 18 while (!q.empty()) {19 TreeNode *p1 = q.front();20 q.pop();21 TreeNode *p2 = q.front();22 q.pop();23 24 if (!p1 && !p2) continue;25 if (!p1 || !p2) return false;26 if (p1->val != p2->val) return false;27 28 q.push(p1->left);29 q.push(p2->right);30 31 q.push(p1->right);32 q.push(p2->left);33 }34 35 return true;36 }37 38 };
[leetCode] Symmetric Tree
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。