Symmetric Tree

来源:互联网 发布:eclipse怎么写sql语句 编辑:程序博客网 时间:2024/06/03 19:15

题目来源LeetCode
题目描述

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following [1,2,2,null,3,null,3] is not:
1
/ \
2 2
\ \
3 3
Note:
Bonus points if you could solve it both recursively and iteratively.

这道题用了两种方法,第一种是DFS的方法,利用队列来存储左右的值进行比较,代码如下:

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    bool isSymmetric(TreeNode* root) {        if(root == NULL) return true;        if(root->left == NULL && root->right == NULL) return true;        queue<TreeNode*>ql,qr;        TreeNode*l,*r;        ql.push(root->left);        qr.push(root->right);        l = root->left;        r = root->right;        while(!ql.empty() || !qr.empty() || l != NULL || r != NULL){            if((l == NULL && r != NULL)|| (l != NULL && r == NULL)) return false;            else if(l != NULL && r != NULL){                if(l->val != r->val) return false;                ql.push(l);                qr.push(r);                l = l->left;                r = r->right;            }            else {                l = ql.front()->right;                r = qr.front()->left;                ql.pop();                qr.pop();            }        }        return true;    }};

第二种算法是用的递归,代码如下:

 bool recursive(TreeNode*l,TreeNode*r){     if(r == NULL && l == NULL) return true;     else if((r == NULL && l != NULL) || (l == NULL && r != NULL)) return false;     if(l->val != r-> val) return false;     else return recursive(l->left,r->right)&&recursive(l->right, r->left); }class Solution {public:    bool isSymmetric(TreeNode* root) {        if(root == NULL) return true;        return recursive(root->left, root->right);    }};