您的位置:首页 > 其它

leetcode-Symmetric Tree 对称树

2015-06-09 09:51 399 查看
class Solution {

public:

vector<int>result;

int l;

bool isSymmetric(TreeNode* root) {

int i,j;

if(root == NULL) return true;

inorder(root);

l=result.size();

for(i=0,j=l-1;i<j;i++,j--)

{

if(result[i]!=result[j])

return false;

}

return true;

}

void inorder(TreeNode* root)

{

if(root==NULL) return;

inorder(root->left);

// if(root->left!=NULL)

result.push_back(root->val);

// if(root->right!=NULL)

inorder(root->right);

}

};

中序遍历,结果不对

递归

class Solution {

public:

bool isSymmetric(TreeNode* root) {

if(!root) return true;

else return symmetric(root->left,root->right);

}

bool symmetric(TreeNode* t1,TreeNode* t2)

{

if(!t1&&!t2) return true;

if(!t2&&t1) return false;

if(!t1&&t2) return false;

if(t1->val!=t2->val) return false;

else return symmetric(t1->left,t2->right)&&symmetric(t1->right,t2->left);

}

};

非递归

class Solution {

public:

bool isSymmetric (TreeNode* root) {

if (!root) return true;

stack<TreeNode*> s;

s.push(root->left);

s.push(root->right);

while (!s.empty ()) {

auto p = s.top (); s.pop();

auto q = s.top (); s.pop();

if (!p && !q) continue;

if (!p || !q) return false;

if (p->val != q->val) return false;

s.push(p->left);

s.push(q->right);

s.push(p->right);

s.push(q->left);

}

return true;

}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: