LeetCode--Symmetric Tree

来源:互联网 发布:邮件服务器软件价格 编辑:程序博客网 时间:2024/06/08 04:42

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.

方法一:递归。每次判断对称的两个节点是否相同,以及递归判断他们对称的子节点是否相同。

/** * 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) return true;        return isSymmetric(root->left,root->right);    }    bool isSymmetric(TreeNode* p,TreeNode* q){        if(!p&&!q) return true;        if(!p||!q) return false;        return (p->val==q->val)&&isSymmetric(p->left,q->right)&&isSymmetric(p->right,q->left);    }};

方法二:非递归。还是用堆栈,基本思路和上面一样,就是注意子节点都是空节点就跳过继续循环。

/** * 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) return true;        stack<TreeNode*>s;        s.push(root->left);        s.push(root->right);        while(!s.empty()){            TreeNode *p=s.top();            s.pop();            TreeNode *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;    }};