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

topic:node

101. Symmetric Tree

Description:this

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For examplecode

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.所謂的對稱,是左右相反位置的節點的值判斷是否相同。ip

2.全部的節點對稱,是能夠從源頭追根溯源的。
    3.只要出現不一樣,便可返回便可,不然繼續進行處理。

代碼以下:it

# 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
相關文章
相關標籤/搜索