[leetcode]Symmetric Tree @ Python


原題地址:https://oj.leetcode.com/problems/symmetric-tree/

題意:判斷二叉樹是否為對稱的。

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

解題思路:這題也不難。需要用一個help函數,當然也是遞歸的。當存在左右子樹時,判斷左右子樹的根節點值是否相等,如果想等繼續遞歸判斷左子樹根的右子樹根節點和右子樹根的左子樹根節點以及左子樹根的左子樹根節點和右子樹根的右子樹根節點的值是否相等。然后一直遞歸判斷下去就可以了。

代碼:

# Definition for a  binary tree node
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    # @param root, a tree node
    # @return a boolean
    def help(self, p, q):
        if p == None and q == None: return True
        if p and q and p.val == q.val:
            return self.help(p.right, q.left) and self.help(p.left, q.right)
        return False
    
    def isSymmetric(self, root):
        if root:
            return self.help(root.left, root.right)
        return True

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM