[Leetcode]Symmetric Tree

来源:互联网 发布:excel数据对比分析 编辑:程序博客网 时间:2024/05/17 08:29

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.

判断数是否对称~不对称的条件有以下三个:(1)左边为空而右边不为空;(2)左边不为空而右边为空;(3)左边值不等于右边值~算法的时间复杂度是树的遍历O(n),空间复杂度同样与树遍历相同是O(logn)~  (写关于树的题目还是不太熟练,还得加强练习)递归代码如下~

class Solution:    # @param root, a tree node    # @return a boolean    def isSymmetric(self, root):        if root is None: return True        return self.helper(root.left, root.right)        def helper(self, root1, root2):        if root1 is None and root2 is None: return True        if root1 is None or root2 is None: return False        if root1.val != root2.val: return False        return self.helper(root1.left, root2.right) and self.helper(root1.right, root2.left)

参考了别人的代码,非递归解法如下~ (非递归解法要自己写还真是有点写不出来,加油吧~)

class Solution:    # @param root, a tree node    # @return a boolean    def isSymmetric(self, root):        if root is None: return True        queue = [[root.left, root.right]]        while queue:            pair = queue.pop(0)            if not (pair[0] or pair[1]):                continue            elif (pair[0] and pair[1]) and pair[0].val == pair[1].val:                queue.append([pair[0].left, pair[1].right])                queue.append([pair[0].right, pair[1].left])            else:                return False        return True


0 0
原创粉丝点击