Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
2.
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
Same tree
|
Symmetric tree
|
class Solution {
public:
bool isSameTree(TreeNode
*p, TreeNode *q) {
if (p==NULL &&
q==NULL) return true;
if ((p!=NULL &&
q==NULL)||(p==NULL&&q!=NULL))
return false;
if
(p->val==q->val)
{
return
isSameTree(p->left,q->left)&isSameTree(p->right,q->right);
}
else
return false;
}
};
class Solution { public: bool isSameTree(TreeNode *p, TreeNode *q) { stack<TreeNode *> st; st.push(p); st.push(q); while(!st.empty()) { p = st.top();st.pop(); q = st.top(); st.pop(); if (p==NULL&&q==NULL) continue; if (p==NULL||q==NULL) return false; if (p->val==q->val) { st.push(p->left); st.push(q->left); st.push(p->right); st.push(q->right); } else return false; } return true; } }; |
class Solution { public: bool helper(TreeNode *left, TreeNode *right) { if (left==right && left==NULL) return true; if ((left==NULL&&right!=NULL)||(left!=NULL && right==NULL)) return false; return ((left->val==right->val)&&helper(left->left,right->right)&&helper(left->right, right->left)); } bool isSymmetric(TreeNode *root) { return root?helper(root->left, root->right):true; } }; Iterative solution
class Solution {
public:
bool isSymmetric(TreeNode
*root) {
if
(root==NULL||(root->left==NULL&&root->right==NULL))
return true;
TreeNode *p =
root->left, *q=root->right;
stack<TreeNode*>
st;
st.push(p);
st.push(q);
while(!st.empty())
{
p =st.top();
st.pop();
q = st.top();
st.pop();
if
(p==NULL&&q==NULL) continue;
if
(p==NULL||q==NULL) return false;
if
(p->val!=q->val) return false;
st.push(p->left);
st.push(q->right);
st.push(p->right);
st.push(q->left);
}
return true;
}
};
|
No comments:
Post a Comment