leetcode-101-Symmetric Tree-二叉樹對稱問題

龍仔發表於2019-02-16

topic:

101. Symmetric Tree 

Description:

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    /    2   2  /  /  3  4 4  3
But the following [1,2,2,null,3,null,3] is not:
1    /    2   2           3    3 Note:
Bonus points if you could solve it both recursively and iteratively.

解題思路:1.所謂的對稱,是左右相反位置的節點的值判斷是否相同。

    2.所有的節點對稱,是可以從源頭追根溯源的。
    3.只要出現不同,即可返回即可,否則繼續進行處理。

程式碼如下:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
from collections import deque
class Solution:
    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if not root:
            return True
        nodes_stack=[root.left,root.right]
        while nodes_stack:
            val_left,val_right=nodes_stack.pop(0),nodes_stack.pop(0)
            if not val_left and not val_right:
                continue
            elif not val_left or not val_right:
                return False
            elif val_left.val!=val_right.val:
                return False
            else:
                nodes_stack.extend([val_left.left,val_right.right,val_left.right,val_right.left])
        return  True

相關文章