Symmetric Tree

来源:互联网 发布:网页游戏网站源码 编辑:程序博客网 时间:2024/06/07 05:20

题目描述:

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.

思路:

可以考虑用2钟方法遍历树,第一种是先访问左子树再访问右子树最后访问根,得到一个输出。第二种是先访问右子树再访问左子树最后访问根,得到第二个输出。然后比较这2输出结果,如果是对称的结果也会是一样的(注意空节点也要输出一个数字,我随便设置了一个8888)。由于之前有过访问树的题,所以我直接用之前的代码改了,比较简单。但应该还有更好的办法。。。。


代码(python):

# Definition for a  binary tree node# class TreeNode:#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution:    # @param root, a tree node    # @return a boolean    def isSymmetric(self, root):        leftout = self.postorderTraversal1(root)        rightout = self.postorderTraversal2(root)        if leftout == rightout:            return True        else:            return False    def postorderTraversal1(self,root):        ans = []        if root is None:            return [8888]        ans+=self.postorderTraversal1(root.left)        ans+=self.postorderTraversal1(root.right)        ans+= [root.val]        return ans    def postorderTraversal2(self,root):        ans = []        if root is None:            return [8888]        ans+=self.postorderTraversal2(root.right)        ans+=self.postorderTraversal2(root.left)        ans+= [root.val]        return ans


0 0