关闭

leetcode 101 Symmetric Tree

标签: algorithmc++leetcode
1140人阅读 评论(0) 收藏 举报
分类:


Symmetric Tree
Total Accepted: 61440 Total Submissions: 194643 My Submissions
                     

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.

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.


c++ 解决方案:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
#include<queue>
using namespace std;
typedef pair<TreeNode*,TreeNode*> nodepair;
class Solution {
public:
    bool isSymmetricRecursive(TreeNode*a,TreeNode*b){
        if(a){
            return b && a->val==b->val && 
                isSymmetricRecursive(a->left,b->right) &&
                isSymmetricRecursive(a->right,b->left);
        }
        return !b;
    }
    bool isSymmetricRecursive(TreeNode*root){
        return !root || isSymmetricRecursive(root->left,root->right);
    }
    bool isSymmetric(TreeNode *root) {
        // Level-order BFS.
        queue<nodepair> q;
        if(root)
            q.push(make_pair(root->left,root->right));
        while(q.size()){
            nodepair p=q.front(); q.pop();
            if(p.first){
                if(!p.second)return false;
                if(p.first->val != p.second->val) return false;
                // the order of children pushed to q is the key to the solution.
                q.push(make_pair(p.first->left,p.second->right));
                q.push(make_pair(p.first->right,p.second->left));
            }
            else if(p.second) return false;
        }
        return true;
    }
};

   


第二种,非递归解决方案:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isSymmetric(TreeNode *root) {
        TreeNode *left, *right;
        if (!root)
            return true;

        queue<TreeNode*> q1, q2;
        q1.push(root->left);
        q2.push(root->right);
        while (!q1.empty() && !q2.empty()){
            left = q1.front();
            q1.pop();
            right = q2.front();
            q2.pop();
            if (NULL == left && NULL == right)
                continue;
            if (NULL == left || NULL == right)
                return false;
            if (left->val != right->val)
                return false;
            q1.push(left->left);
            q1.push(left->right);
            q2.push(right->right);
            q2.push(right->left);
        }
        return true;
    }
};


/**
 * 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*> sk;
        sk.push(root->left);
        sk.push(root->right);

        TreeNode* pA, *pB;
        while(!sk.empty()) {
            pA = sk.top();
            sk.pop();
            pB = sk.top();
            sk.pop();

            if(!pA && !pB) continue;
            if(!pA || !pB) return false;
            if(pA->val != pB->val) return false;

            sk.push(pA->left);
            sk.push(pB->right);
            sk.push(pA->right);
            sk.push(pB->left);
        }

        return true;
    }
};


 

c版本:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */

bool checkNodes(struct TreeNode* a, struct TreeNode* b)
{
    if(a == NULL && b == NULL)
    {
        return true;
    }

    if(a == NULL || b == NULL)
    {
        return false;
    }
    if(a->val != b->val)
    {
        return false;
    }
    return checkNodes(a->left, b->right) && checkNodes(a->right, b->left);
}
bool isSymmetric(struct TreeNode* root) {
    if(root == NULL)
    {
        return true;
    }
    return checkNodes(root->left, root->right);
}


递归方案:

bool isSymmetric(TreeNode *root) {
        if (!root) return true;
        return helper(root->left, root->right);
    }

    bool helper(TreeNode* p, TreeNode* q) {
        if (!p && !q) {
            return true;
        } else if (!p || !q) {
            return false;
        }

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

        return helper(p->left,q->right) && helper(p->right, q->left); 
    }


python版本:

class Solution:
    # @param {TreeNode} root
    # @return {boolean}
    def helper(self, a, b):
        if a is None and b is None:
            return True
        if a is None and b is not None:
            return False
        if a is not None and b is None:
            return False
        if a.val != b.val: 
            return False
        return self.helper(a.left, b.right) and self.helper(a.right,b.left)
    def isSymmetric(self, root):
        if root is None:
            return True
        return self.helper(root.left, root.right)

class Solution:
    # @param {TreeNode} root
    # @return {boolean}
    def isSymmetric(self, root):
        # no tree
        # is identical
        if root is None: return True
        if not self.is_identical(root.left, root.right): return False

        queue = []
        # root is identical
        # proceed to queue up the next level
        # (node, depth)

        if root.left:
            enqueue(queue, (root.left, 1))

        if root.right:
            enqueue(queue, (root.right, 1))

        while queue:

            same_level = True
            level = []
            while same_level:
                # still the same level
                if len(queue) > 0 and (len(level) == 0 or level[-1][1] == queue[0][1]):
                    child = dequeue(queue)
                    level.append(child)
                    # enqueue children now to maintain level order
                    # add to the depth
                    if child[0].left:
                        enqueue(queue, (child[0].left, child[1]+1))
                    if child[0].right:
                        enqueue(queue, (child[0].right, child[1]+1))   
                else:
                    same_level = False

            # symmetrical has to be even
            if len(level) % 2 != 0: return False
            while level:
                # grab the two extreme ends 
                (left_node, _), (right_node, _) = level.pop(0), level.pop()
                if not self.is_identical(left_node, right_node): return False


        return True

    def is_identical(self, left, right):
        # if any of them is none, they need to be both none
        if left is None or right is None:
            return left == right

        # their value should equal
        if left.val != right.val:
            return False

        # if left has a left, then right needs to have right
        if left.left:
            if right.right is None:
                return False


        # if left has a right, then right needs to have left
        if left.right:
            if right.left is None:
                return False

        return True




def enqueue(queue, item):
    queue.append(item)

def dequeue(queue):
    return queue.pop(0)


1
0
查看评论
发表评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场

【LeetCode-面试算法经典-Java实现】【101-Symmetric Tree(对称树)】

【101-Symmetric Tree(对称树)】【LeetCode-面试算法经典-Java实现】【所有题目目录索引】原题  Given a binary tree, check whether it...
  • DERRANTCM
  • DERRANTCM
  • 2015-08-07 07:29
  • 3623

Leetcode-Symmetric Tree——判断二叉树是否对称

题目 Symmetric Tree  Total Accepted: 12814 Total Submissions: 40358My Submissions Given a bina...
  • disappearedgod
  • disappearedgod
  • 2014-04-20 01:00
  • 2044

【leetcode 二叉树对称判断】Symmetric Tree

1、题目 2、分析 3、daim
  • u012162613
  • u012162613
  • 2014-11-17 18:03
  • 2244

Leetcode 101. Symmetric Tree( C++版)

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). Fo...
  • Mary19920410
  • Mary19920410
  • 2017-04-09 16:42
  • 146

[Leetcode] 101. Symmetric Tree 解题报告

题目: Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center)....
  • magicbean2
  • magicbean2
  • 2017-04-21 10:55
  • 164

101.[Leetcode]Symmetric Tree

题意:判断一个二叉树是不是对称的我的思路: 递归 但是不是一般的那种递归,那种递归我是想不出来的,因为觉得子节点是否是对称和父节点着实没什么关系。我用递归遍历一个节点的左右节点,并记录在栈里,同时...
  • qq_28057541
  • qq_28057541
  • 2016-05-14 14:20
  • 141

Leetcode 101. Symmetric Tree

题目描述如下: 解决思路:这道题是我在BFS分类中找的,所以就试图用广搜的想法来解决,关键思路就是 1、left对应right 2、left->left对应right->right 3、lef...
  • jessir
  • jessir
  • 2017-04-24 11:27
  • 179

LeetCode题解-101-Symmetric Tree

原题 链接:https://leetcode.com/problems/symmetric-tree/ 解法概览 本题共有3种解法,解法1为别人的解答,解法2为参考别人思路后改造...
  • WangT443
  • WangT443
  • 2016-07-13 10:24
  • 375

【LeetCode】101. Symmetric Tree 解题报告

转载请注明出处:http://blog.csdn.net/crazy1235/article/details/51471280Subject 出处:https://leetcode.com/pro...
  • crazy1235
  • crazy1235
  • 2016-05-30 23:06
  • 6226

LeetCode 101 Symmetric Tree(对称树)(*)

翻译给定一个二叉树,检查它是否是它本身的镜像(也就是说,中心对称)。例如,这个二叉树是对称的: 1 / \ 2 2 / \ / \ 3 4 4 3但是下面这个却不是: ...
  • NoMasp
  • NoMasp
  • 2016-01-21 14:04
  • 1463
    公众号,github
    公众号:     老王和他的IT界朋友们
    欢迎投稿:  shiter@live.cn
    QQ交流群:  593683975
    加群问题:抛硬币正面上的期望?

    我们想用一段音乐,几张图片,
    些许文字绘制的IT圈心路历程,
    为攻城狮,为程序员带来更多的人文关怀。

    投稿原创文章有稿费,杂志等福利!!!



    github:  https://github.com/wynshiter
    个人资料
    • 访问:1269978次
    • 积分:14014
    • 等级:
    • 排名:第1030名
    • 原创:189篇
    • 转载:51篇
    • 译文:74篇
    • 评论:704条
    博客专栏
    百度统计
    微信公众号
      微信公众号
      老王和他的IT界朋友们