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.
class Solution { public: bool isSameTree(TreeNode *p, TreeNode *q) { if (!p && !q){ return true; } if (!p && q || !q && p){ return false; } return isSameTree(p->left,q->left) && isSameTree(p->right,q->right) && p->val == q->val; } void build(TreeNode * root,TreeNode *& newroot){ if (!root){ return; } if (!newroot){ newroot = new TreeNode(root->val); build(root->left,newroot->right); build(root->right,newroot->left); } } bool isSymmetric(TreeNode *root) { // Start typing your C/C++ solution below // DO NOT write int main() function if (!root){ return true; } TreeNode * newroot = NULL; build(root,newroot); return isSameTree(root,newroot); } };
浙公网安备 33010602011771号