首页 > 代码库 > LeetCode[Tree]: Symmetric Tree
LeetCode[Tree]: Symmetric Tree
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
Recursive Algorithm
class Solution { public: bool isSymmetric(TreeNode *root) { return root ? isSymmetric(root->left, root->right) : true; } private: bool isSymmetric(TreeNode *left, TreeNode *right) { if (!left && !right) return true; if ( left && !right) return false; if (!left && right) return false; if (left->val != right->val) return false; if (!isSymmetric(left->left, right->right)) return false; if (!isSymmetric(left->right, right->left )) return false; return true; } };
Iterative Algorithm
class Solution { public: bool isSymmetric(TreeNode *root) { if (!root) return true; stack<TreeNode *> leftStack, rightStack; leftStack.push(root->left); rightStack.push(root->right); while (!leftStack.empty()) { TreeNode *left = leftStack.top(), *right = rightStack.top(); leftStack.pop(); rightStack.pop(); if (!left && !right) continue; if (!left && right) return false; if ( left && !right) return false; if (left->val != right->val) return false; leftStack.push(left->left ); rightStack.push(right->right); leftStack.push(left->right); rightStack.push(right->left); } return true; } };
LeetCode[Tree]: Symmetric Tree
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。