美文网首页
LeetCode 101. Symmetric Tree

LeetCode 101. Symmetric Tree

作者: 洛丽塔的云裳 | 来源:发表于2020-04-16 21:43 被阅读0次

0. 题目

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. c++版本

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

    }

版本2,对二叉树进行两次排序,第1次: root->left->right. 第2次: root->right->left; 然后对比结果

 void preOrder(TreeNode* root, vector<int>& result, int flag){
        if(root){
            result.push_back(root->val);
            if (flag == 0) {
                preOrder(root->left, result, flag);
                preOrder(root->right, result, flag);
            }
            else {
                preOrder(root->right, result, flag);
                preOrder(root->left, result, flag);
            }
        }
        else
            result.push_back(INT_MIN);
    }
   
    bool isSymmetric(TreeNode* root) {        
        vector<int> result1, result2;
        preOrder(root, result1, 0);
        preOrder(root, result2, 1);
        return (result1 == result2);
    }

2. python版本

    def preOrder(self, root, result, flag):
        if root:
            result.append(root.val)
            if flag == 0:
                self.preOrder(root.left, result, flag)
                self.preOrder(root.right, result, flag)
            else:
                self.preOrder(root.right, result, flag)
                self.preOrder(root.left, result, flag)
        else:
            result.append(2147483647)
        
    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        result1, result2 = [], []
        self.preOrder(root, result1, 0)
        self.preOrder(root, result2, 1)
        if result1 == result2:
            return True
        else:
            return False

方法2, 使用递归

class Solution(object):
    def isMirror(self, p, q):
        """
        """
        if not p and not q:
            return True
        if  not p or not q:
            return False
        if p.val != q.val:
            return False
        return self.isMirror(p.left, q.right) and self.isMirror(p.right, q.left)
    
    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        return self.isMirror(root, root);

相关文章

网友评论

      本文标题:LeetCode 101. Symmetric Tree

      本文链接:https://www.haomeiwen.com/subject/virjvhtx.html